banana
banana

Reputation: 23

Why is my Select Statement not working properly?

I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.

Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.

my code

$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing

Please help me find out what's wrong. Hehe thanks in advance.

Upvotes: 0

Views: 120

Answers (3)

David de Kleer
David de Kleer

Reputation: 116

It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):

// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);  
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"]; 

Upvotes: 1

banana
banana

Reputation: 23

Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.

Carelessness again is the cause for all these. :) hehe

This is where the error is coming from

<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>

I have assigned a variable on a value with extra spaces/character? So the code must look like this.

<input type="hidden" name="idsend" value="'.$row['id'].'"/>

It must be assigned properly to work smoothly with the select statement. I guess echo-ing the values isn't enough to see if there's something wrong.

Sorry for the trouble.

Upvotes: 0

Lars Beck
Lars Beck

Reputation: 3584

First of all, you shouldn't use mysql_* functions anymore.

You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.

while ( $row = mysql_fetch_array( $edit ) ) {
    printf( 'ID: %s', $row['id'] );
}

Upvotes: 0

Related Questions