0

How to place a php variable into query?

$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname='$shopname'')->fetchAll(PDO::FETCH_ASSOC);

This is not working, the error message show: "Parse error: syntax error, unexpected '$shopname' (T_VARIABLE)"

5 Answers 5

4

No

Do not insert parameters this way. You should be using bindParam

$statement = $db->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$statement->bindParam(':shopname', $shopname, PDO::PARAM_STR);
$statement->execute();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but how to retrieve the value and show in echo? Notice: Array to string conversion
1

If $shopname is coming from an untrusted source, you are wide open to SQL injection. To fix this, you should make use of PDO and it's prepared statement API:

$query = $pdo->prepare("SELECT shopid FROM shop WHERE shopname = ?");
$query->bindValue(1, $shopname, PDO::PARAM_STR);
$query->execute();

$shopid = $query->fetchAll(PDO::FETCH_ASSOC);

Comments

0

if you support the PDO ,why not use the prepare, and it is more safe.

$stmt = $pdo->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$stmt->bindParam(':shopname', $shopname);
$shopname = $yourdefined;
$stmt->execute();

$stmt->bindColumn(1, $shopid);
    while($stmt->fetch()){
      echo $shopid,PHP_EOL;

    }

Well,you can also use the base sql like this:

$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname=\'{$shopname}\'')->fetchAll(PDO::FETCH_ASSOC);

Comments

0

You weren't wrapping your query properly.

$shopid = $pdo->query("SELECT shopid FROM `shop` WHERE `shopname`='$shopname'");

1 Comment

No, this is terrible. You should be using bindParam. Also, you have an SQL syntax error.
-2

Try This:

$query = "SELECT shopid FROM shop WHERE shopname= '".$shopname."'";

$result = mysql_query($query);

1 Comment

Please explain What is wrong with this query?? $shopname is PHP variable consist of shopname

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.