简体   繁体   中英

How to write MySQL query that uses a PHP variable?

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

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();

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);

您没有正确包装查询。

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

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);

'...' . $shopname . '...'

Using point to join more than 1 string

Try This:

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

$result = mysql_query($query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM