嘿,我是PHP / MySqli的新手,如果给定ID的Scanstatus字段已经是"扫描",我想在更新前检查。如果它已经扫描显示消息为"已经扫描"否则更新。
以下代码仅更新,并且不检查是否已存在。
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id";
$result = mysqli_query($connection,$query);
if (!$result) {
die('Error' . mysqli_error($connection));
}
else
{
echo "Successfully updated";
}
}
?>
答案 0 :(得分:0)
尝试以下php代码
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
else{
if(isset($_POST['Submit']))
{
$sql = "UPDATE sales SET ScanStatus = 'Scanned' WHERE id = '$id'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "Successfully updated";
} else {
die('Error' . mysqli_error($connection));
}
}
}
单击SUBMIT按钮“isset($ _ POST ['Submit'])”将为true且直接进入if语句。然后运行sql命令,如果有任何结果,sql查询受影响进入下一个if语句后,条件“$ result-&gt; num_rows&gt; 0”然后回显“成功更新”。
答案 1 :(得分:0)
据我了解,您只想在ScanStatus
字段不是Scanned
因此,您可以修改现有的查询,而无需获取记录:
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
只需将查询更改为上方并使用:
if(mysqli_affected_rows($result) > 0 ){
这是完整的代码:
<?php
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno()) {
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit'])) {
$id = $_POST['id'];
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = $id AND `ScanStatus` != 'Scanned'";
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
}
else {
echo 'Already Scanned';
}
}
答案 2 :(得分:-1)
您可以使用此代码:
使用if(mysqli_affected_rows($mysqli) > 0 )
或根本不进行比较。
用以下代码替换您的代码:
<?php
$id = $_POST['id'];
$connection = mysqli_connect("localhost", "username", "passwd","dbname");
if(mysqli_connect_errno())
{
echo "failed to connect " . mysqli_connect_error();
}
if(isset($_POST['Submit']))
{
$my_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = ". $id . " AND `ScanStatus` = 'Scanned'");
if(mysqli_num_rows($my_query) > 0){
echo "Already ScanStatus is Scanned";
}
else{
$query = "UPDATE `sales` SET `ScanStatus` = 'Scanned' WHERE `id` = ".$id;
//echo $query;die;
$result = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) > 0 ){
echo "Successfully updated";
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `sales` WHERE `id` = '$id' LIMIT 1");
$new_info = mysqli_fetch_array($new_query);
echo "<pre>"; print_r($new_info);
}
else
{
echo "Not updated";
}
}
}
?>