0

I'm having issues placing a PHP variable in MySQL string,

<?php
$con=mysqli_connect("***","***","***","***");

function getItem($itemNo)
{
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$itemNo'");

    echo $itemNo;
    echo "<br>";
    while($row = mysqli_fetch_array($result))
    {
        echo $row['product_id'] . " " . $row['product_name'];
        echo "<br>";
    }
}
getItem(1001);
mysqli_close($con);

?>

The page shows my echo of the $itemNo, but thats all. If I just do select * from products, it gives my entire table like it should, so I know the database is working, so I've narrowed it down to the placement of the variable.

EDIT:

product_id column is an int and also the primary key.

7
  • what is the type of product_id ? if the type is int or bigint then just use $result = mysqli_query($con,"SELECT * FROM products WHERE product_id = $itemNo"); Commented Apr 21, 2014 at 6:31
  • its an int, i gave that a go, and it didnt work. Commented Apr 21, 2014 at 6:37
  • 1
    Is that your actual database login in your supplied code? Surely that's something you should be keeping to yourself? Commented Apr 21, 2014 at 6:41
  • 1
    As Jimmy mentioned, you've left your login data. An edit was done to remove it, but people can always see the history. It would be advisable to change both login and password on your end. Commented Apr 21, 2014 at 6:43
  • 1
    Just a sidenote, which you probably already know. Dont do this "SELECT * FROM products WHERE product_id = '$itemNo'" unless you are making software just for yourself. One can SQL-inject to that code pretty much anything they want. Commented Apr 21, 2014 at 6:55

2 Answers 2

2

You can try a prepared statement to make using variables in your queries easier.

$stmt = $con->prepare("SELECT * FROM products WHERE product_id=?");
$stmt->bind_param($itemNo);
$stmt->execute();
$stmt->close();
Sign up to request clarification or add additional context in comments.

Comments

1
 $result = mysqli_query($con,"SELECT * FROM products WHERE product_id = " .$itemNo );

Comments

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.