0

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".

2
  • are you posting information to that script? can we see your form? Commented Oct 15, 2013 at 2:33
  • Yes, I have the form before this page grab the user's email. Commented Oct 15, 2013 at 2:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I did as you said and kept my code above the same except for your changes. $item_name now returns NULL. Was there something else I should have changed that I'm not doing?
Well either, your $rows variable is null, or the $data['name'] variable is null. I'm not sure what $db manager you are using, but use the numRows method on it to verify the $ir->fetchRows() is actually returning rows so we can determine which of the two variables is our culprit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.