我想在插入新记录之前检查是否已存在记录。但它到目前为止还没有工作,这是脚本:
<?php
session_start();
$uname = $_SESSION['username'];
$friend = $_GET["newfriend"];
$db = new mysqli("localhost", "...", "....", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
$checkexist = $db->query("SELECT * FROM friends WHERE (username_own='$uname', username='$friend')");
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0) {
//run the query to insert the row
$stmt->execute();
}
答案 0 :(得分:4)
尝试这样的事情:
<?php
/* Check if user exists */
$query = "SELECT count(1) FROM friends WHERE username_own=? AND username=?";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->bind_result($count_rows);
$stmt->fetch();
$stmt->close();
}else die("Failed to prepare");
/* If user doesn't exists, insert */
if($count_row == 0){
$query = "INSERT INTO friends (`username_own`, `username`) VALUES (?,?)";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare!");
}
答案 1 :(得分:0)
试试这个:
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0 || $checkexist->mysqli_num_rows <> 0) {
//run the query to insert the row
$stmt->execute();
}
答案 2 :(得分:0)
$checkexist->mysqli_num_rows
错了。它只是
$checkexist->num_rows
或者您可以使用
mysqli_num_rows($checkexist)
希望这有帮助。
答案 3 :(得分:0)
使用简单的INSERT IGNORE ...
或INSERT ... ON DUPLICATE KEY UPDATE ...
替换大部分代码。
后者允许您在记录已存在的情况下更改列(基于任何PRIMARY或UNIQUE键)。