Forum Moderators: coopster

Message Too Old, No Replies

PHP Scripting - Help Required

         

Jamier101

7:41 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



I'm quite new to using PHP to retrieve information for a MySQL database and I was hoping that someone could point me in the right direction as I'm stuck :-(

This is my form:

<body>
<?php
mysql_connect("localhost", "root", "bigboldy") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("test") or die(mysql_error());
echo "Connected to Database";
?>

<form name="form1" method="POST" action="find_name.php">
<select name="name">
<option value="jamie">Jamie</option>
<option value="helen">Helen</option>
<option value="pauline">Pauline</option>
<option value="david">David</option>
</select>
<input name="Submit" type="submit" value="submit"/>
</form>

</body>


I am trying to use the form to find the surname and email address that I have stored in my table $test_mysql and have tried using the following script but current I'm having no luck.


<body>
<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

&name = $_POST['name'];

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get data from mysql
$sql = "SELECT 'name', 'lastname', 'email' FROM $tbl_name WHERE 'name'=$name";
$query = mysql_query($sql);

while ($row = mysql_fetch_array($query)) {
echo "$row['name']".
echo "$row['lastname']".
echo "$row['email']";
}

else {
echo "ERROR";
}

// Close connection
mysql_close();
?>
</body>


I don't get an error when I run the script but nothing is returned so I'm hoping that I'm close but I might have thought it all through wrong! :-S

Frank_Rizzo

8:46 pm on Sep 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Error in the select. You have single quotes around the field name not the value. Try this:

"SELECT name, lastname, email FROM $tbl_name WHERE name='$name'";

One tip for this kind of thing is to echo out the select string. Your original string was this:

$sql = "SELECT 'name', 'lastname', 'email' FROM $tbl_name WHERE 'name'=$name";

If you add this after it:

echo $sql;

You will see what you are feeding MySQL and would this spot the error. If the error was not obvious straight away then cut and paste the echo into a MySQL query string like phpmyadmin or on the command line. You should get an error similar to 'error near '.... '

Jamier101

9:46 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



I find that using the
 echo $sql; 
statement doesn't show me anything in the browser.

I've adjusted my code although I'm still having no luck :-S


<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

&name = $_POST['name'];

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get data from mysql
$sql = "SELECT name, lastname, email FROM $tbl_name WHERE name='$name'";
echo $sql;
$query = mysql_query($sql);

while ($row = mysql_fetch_array($query)) {
echo "$row['name']".
echo "$row['lastname']".
echo "$row['email']";
}

else {
echo "ERROR";
}

// Close connection
mysql_close();
?>

Matthew1980

9:51 pm on Sep 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Jamier101,

Welcome to the Forum!

Your not too far off from what you need, firstly get this working then you can worry about the technical 'security' stuff later.

This script will not work as it stands at the moment as you are not setting things up properly, most notably the variable that you are passing from page to page (the element name from the select/option).

In the 'find_name.php' (which is hopefully where the second part of the code is written) you need to have used the $_POST 'super' global array (this is created/populated when you submit the form), so what you need is something like this:-

<body>
<body>
<?php
//Turn error reporting on, this will help loads when your developing!
error_reporting(E_ALL);

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

//Assign the vars from the previous page
$name = strip_tags(mysql_real_escape_string($_POST['name']));//make this safer for the DB

// Connect to server and select database.
$conn = mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name, $conn)or die("cannot select DB");

// Get data from mysql
//Use the correct quoting quotes, Single quotes for string values & not column names
//Back ticks for the column names & not values (this is optional, you will find out later on! ;))
//Int's dont need quoting, but strings do when used in the sql

$sql = "SELECT `name`, `lastname`, `email` FROM `".$tbl_name."` WHERE `name` = '".$name."';
$query = mysql_query($sql, $conn) or die("cannot connect");

//Once the connection handle has been established, you don't need to re reference it because the functions
//always use the last known connection that is still available, hope that makes sense

while ($row = mysql_fetch_array($query)) {
echo $row['name']."<br>";
echo $row['lastname']."<br>";
echo $row['email']."<br>";
}

//cant have an else on a while; else's belong on an if...

// Close connection
// no need for this function as the connection automatically closes after the last query has finished ;)
mysql_close();
?>
</body>


Hope as this all makes sense to you now, any problems just post back on the forum, and someone on here can walk you through it.

Cheers,
MRb

Jamier101

10:09 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



When I read through the code it seems to make more sense, I have a php page called name.php where the front-end is stored:


<?php
mysql_connect("localhost", "root", "bigboldy") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("test") or die(mysql_error());
echo "Connected to Database";
?>

<form action="find_name.php" method="post" name="form1">
<select name="name">
<option value="Jamie">Jamie</option>
<option value="Helen">Helen</option>
<option value="Pauline">Pauline</option>
<option value="David">David</option>
</select>
<input name="Submit" type="submit" value="submit"/>
</form>


I made a little modification to your code because it appeared that a " was missing, I think I've done right.


<?php
//Turn error reporting on, this will help loads when your developing!
error_reporting(E_ALL);

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

//Assign the vars from the previous page
$name = strip_tags(mysql_real_escape_string($_POST['name']));//make this safer for the DB

// Connect to server and select database.
$conn = mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name, $conn)or die("cannot select DB");

// Get data from mysql
// Use the correct quoting quotes, Single quotes for string values & not column names
// Back ticks for the column names & not values (this is optional, you will find out later on! ;))
// Int's dont need quoting, but strings do when used in the sql

$sql = "SELECT `name`, `lastname`, `email` FROM `".$tbl_name."` WHERE `name` = '".$name."'";
$query = mysql_query($sql, $conn) or die("cannot connect");

//Once the connection handle has been established, you don't need to re-reference it because the functions
//always use the last known connection that is still available, hope that makes sense

while ($row = mysql_fetch_array($query)) {
echo $row['name']."<br>";
echo $row['lastname']."<br>";
echo $row['email']."<br>";
}

//cant have an else on a while; else's belong on an if...

// Close connection
// no need for this function as the connection automatically closes after the last query has finished ;)
mysql_close();
?>


The interesting thing is that when I click submit no errors are returned.

Matthew1980

10:45 pm on Sep 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



All code typed OTF so could contain typo's but hopefully not! ;-p

Hi there Jamie101,

<form action="find_name.php" method="post" name="form1">
<select name="name">
<option value="Jamie">Jamie</option>
<option value="Helen">Helen</option>
<option value="Pauline">Pauline</option>
<option value="David">David</option>
</select>
<input name="Submit" type="submit" value="submit"/>
</form>


There is no need for the DB connection to be in this part at this point in time. just use the form on the page...

Then change your find_name.php file to this so that you have more control over the process once the submit button has been actioned

<?php
//Catch the form being processed
if(isset($_POST['submit']) && ($_POST['submit'] == "submit")){

//Turn error reporting on, this will help loads when your developing!
error_reporting(E_ALL);

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

//Assign the vars from the previous page
$name = strip_tags(mysql_real_escape_string($_POST['name']));//make this safer for the DB

// Connect to server and select database.
$conn = mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name, $conn)or die("cannot select DB");

//added the echo so that you can see if things are set correctly (if they are you will see a name in the vars place ;))
echo $sql = "SELECT `name`, `lastname`, `email` FROM `".$tbl_name."` WHERE `name` = '".$name."'";
$query = mysql_query($sql, $conn) or die("cannot connect");

while ($row = mysql_fetch_array($query)) {
echo $row['name']."<br>";
echo $row['lastname']."<br>";
echo $row['email']."<br>";
}
}
else{
//if these files are in the same directory, and 'name' is the form this will redirect you back there
header("location: name.php");
}
?>


Just ensure as both of these files are in the same directory & that you are in your htdocs/www folder of your server/localhost & that your database has everything spelled correctly that you are referencing.

Hope that this does it this time!

Cheers,
MRb

Jamier101

11:05 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



That's interesting because it appears to always route back to the starting point so somewhere along the line something isn't linking together.

I've loaded the MySQL Command Line Client and I can definitely logging in and pulling data up in there so its not an incorrect password, database or table name. I originally put the test connection script on the main name.php page just so I could check that a connection had been established before I went any further... the plot thickens...

Matthew1980

11:25 pm on Sep 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Jamier101,

Change this line..

>>if(isset($_POST['Submit']) && ($_POST['Submit'] == "submit")){

This will work, the form uses a capital letter for the name attribute (name="Submit") so change that and all will be well with the script.

CaPiTaL lEtTeRs are the SINGLE most common fault with scripts methinks ;-p

Cheers,
MRb

Jamier101

11:32 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



aha!

It works, I mean it returned this SELECT `name`, `lastname`, `email` FROM `test_mysql` WHERE `name` = '' but it worked.

Jamier101

11:34 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



I'm assuming that, that means the script is trying to looks for name, lastname and email in the test_mysql table although the field name is currently blank so I need to find out why its not bringing the vale `name` through from the first page?

Jamier101

11:46 pm on Sep 11, 2010 (gmt 0)

10+ Year Member



If I comment out the second that strips the tags then it works a treat:

//Assign the vars from the previous page
//$name = strip_tags(mysql_real_escape_string($_POST['name']));//make this safer for the DB

// This section works fine like this :)
$name=$_POST['name'];

Matthew1980

7:06 am on Sep 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Jamier101,

Ok then that's some progress! Sorry I didn't reply, I had gone to bed, it had been an extraordinarily long day for me, anyway, good news is that I have got it functional for you now since I slept on it!

Have a read of this revised version:-

<?php
//Turn error reporting on, this will help loads when your developing!
error_reporting(E_ALL);

//Catch the form being processed
if(isset($_POST['Submit']) && ($_POST['Submit'] == "submit")){

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name

// Connect to server and select database.
$conn = mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name, $conn)or die("cannot select DB");

//Assign the vars from the previous page
//still assign the security functions to the $_POST value
//Be aware though, that 'mysql_real_escape_string()' requires a DB connection to work
//but because there is already a connection going at this point in the script, the function
//will automatically pick it up without you needing to reference it in the function.
//if it doesn't pick it up just change the comments over

//they should both work though!
//$name = strip_tags(mysql_real_escape_string($_POST['name'], $conn));
$name = strip_tags(mysql_real_escape_string($_POST['name']));

//do the Sql query - you should see a value there now too ;)
echo $sql = "SELECT `name`, `lastname`, `email` FROM `".$tbl_name."` WHERE `name` = '".$name."'";
$query = mysql_query($sql, $conn) or die("cannot connect");

//see if the query returned anything ie > 'more than' 0 rows
if(mysql_num_rows($query) > 0){

//loop through the results
while ($row = mysql_fetch_array($query)) {
echo $row['name']."<br>";
echo $row['lastname']."<br>";
echo $row['email']."<br>";
}
//close while loop

}else{
//set up the handler just in case the query returns no results!
echo "The query returned no results";

//optional, but if there is nothing else to do with the script you can kill it
exit;
}

//close the if
}
else{
//set the 'error handler' part of the script up
//if these files are in the same directory, and 'name' is the form this will redirect you back there
header("location: name.php");
}
//close the else
?>


Right, hopefully you will understand the little amendment that I had to do, this *should* now function as you need it to. You can now format things as you wish using css/html or tables, up to you ;)

Have fun!

Cheers,
MRb

Jamier101

10:55 am on Sep 12, 2010 (gmt 0)

10+ Year Member



Thanks Matthew1980 its all starting to come together now :)

I guess sleep is an amazing thing! I'm hoping to expand on this today and have my basic pages set up by dinner... only 8 hours :)