簡體   English   中英

mysqli_num_rows在MySQLi和PHP中不起作用

[英]mysqli_num_rows not working in MySQLi with PHP

我想檢查一下是否存在記錄,然后再插入新記錄。 但這到目前為止還行不通,這是腳本:

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

嘗試這個:

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

$checkexist->mysqli_num_rows錯誤。 只是

$checkexist->num_rows

或者你可以使用

mysqli_num_rows($checkexist)

希望這可以幫助。

用簡單的INSERT IGNORE ...INSERT ... ON DUPLICATE KEY UPDATE ...替換大多數代碼。

如果記錄已經存在(基於任何PRIMARY或UNIQUE鍵),則后者使您可以更改列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM