user2766423
user2766423

Reputation: 167

Constructing a query using a php post variable

I have a database table with user info: name, email and item they committed to donate. I'd like to display what item they own on the web page, so I've constructed this query:

$email  = (isset($_POST['email'])) ? $_POST['email'] : '';

$i = "SELECT required_items.name
      FROM required_items LEFT JOIN donations ON donations.item_id=required_items.id 
      WHERE donations.email = '" .$email. "' ";

$ir = $db->query($i);
$rows = $ir->fetchAll();

foreach($rows as $data){
$item_name = $data['name'];
}

Then later when I display the info:

<tr>
   <td><label>Item</label></td>
   <td><input type="text" name="name" value="<?php echo $item_name; ?>"></td>
</tr>

When I run the query and replace ".$email." with an email address, the query works correctly and I am able to see their donation in phpmyadmin, but as of right now with this variable in the code I only get something that just says Array.

How can I display the correct information? I eventually want it sent to the user via email so this would be very helpful.

EDIT: I've applied the advice given by STLMikey and now the $item_name displays "NULL".

Upvotes: 0

Views: 53

Answers (1)

STLMikey
STLMikey

Reputation: 1210

Your code is very vulnerable to SQL injection attacks as it stands. You NEED to re-evaluate that SQL.(http://en.wikipedia.org/wiki/SQL_injection)

To actually answer your question though, your variable named $item_name is a collection of all the rows returned by your query. You need to loop over it to extract the desired name from each row...something like the following:

$rows = $ir->fetchAll();
foreach($rows as $data){
    $item_name = $data['name'];
}

If you can't figure out why something is printing Array() to the screen, try calling print_r($var) on your variable to view it's contents. That will print the contents of an array so you can see the internals.

Upvotes: 1

Related Questions