gpt4 book ai didi

php - mysqli_num_rows 不能在 MySQLi 中使用 PHP

转载 作者:行者123 更新时间:2023-11-29 01:39:38 25 4
gpt4 key购买 nike

我想在插入新记录之前检查是否已经存在记录。但到目前为止它还不起作用,这是脚本:

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

最佳答案

尝试这样的事情:

<?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!");
}

关于php - mysqli_num_rows 不能在 MySQLi 中使用 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28612682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com