简体   繁体   English

php更新sql和查询

[英]php Update sql and Query

I want to do a query in php, output the data on the page and then modify it in the database.我想在php中做一个查询,输出页面上的数据,然后在数据库中进行修改。

How do I do that?我怎么做?

Currently I do it like this but it dose not work:目前我这样做,但它不起作用:

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM pics WHERE id = '$id'";
$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       $dir = $row["dir"];
       $likes = $row["likes"];
    }

$sqlq = "UPDATE pics SET likes='$likes+1' WHERE id='$id'";

$conn->query($sqlq);

$conn->close();

But the like dose not add to the database.但是类似的不会添加到数据库中。

If you echo your $sqlq out using如果您使用回显您的 $sqlq

echo $sqlq;

you'll see that the '$likes+1' isn't doing what you expect.你会看到'$likes+1'没有按照你的预期做。

You could really simplify it by doing你真的可以通过这样做来简化它

$sqlq = "UPDATE pics SET likes=likes+1 WHERE id='$id'";

which removes any risk of two users updating the database at teh same time overwriting each other.这消除了两个用户同时更新数据库相互覆盖的风险。

But you should really check out using "parameterized queries" as that would solve all your problems (and may your queries safer).但是您真的应该检查使用“参数化查询”,因为这可以解决您的所有问题(并且您的查询可能更安全)。 Check the examples in the manual http://php.net/manual/en/mysqli-stmt.bind-param.php检查手册http://php.net/manual/en/mysqli-stmt.bind-param.php 中的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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