How to get affected rows using mysqli?

醉酒当歌 提交于 2021-02-16 20:09:05

问题


I create function for make query in database:

function mysqli($query){
    $mysqli = new mysqli('test','test','test','test');
    if (mysqli_connect_errno()) {
        printf("Bad connect: %s\n", mysqli_connect_error());
        exit();
    }
    $result = $mysqli->query("SET NAMES utf8");
    $result = $mysqli->query("set character_set_client='utf8'");
    $result = $mysqli->query("set collation_connection='utf8_general_ci'");
    $result = $mysqli->query($query);

    $mysqli->close();
    return $result;
};

In next step I want get count affected rows.

For this I make:

$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2->affected_rows;

But I get Notice: Trying to get property of non-object on line echo $res2->affected_rows;

How to get count of affected_rows?


回答1:


Remove the line:

$mysqli->close();

from the function. and this will work.

function mysqli($query){

$mysqli = new mysqli('test','test','test','test');
if (mysqli_connect_errno()) {
    printf("Bad connect: %s\n", mysqli_connect_error());
    exit();
}
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$arr = array($result,$mysqli);
return $arr;
}

Amd the use like this:

$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2[1]->affected_rows;

And your result will be in this variable: res2[0];

Read this answer: mysqli_affected_rows() expects parameter 1 to be mysqli, object given




回答2:


This function is pointless and harmful.

And should never be used.

All other answer told you to remove most useless parts. While what you really have to remove is connection part. Which makes whole function useless.

And even harmful, as you will kill your MySQL server by connecting every time you are going to run a query.

And even more harmful as it doesn't support prepared statements.




回答3:


Remove $mysqli->close(); And make use of

$mysqli->query("INSERT INTO Table (name, value) VALUES ('$name', '$value')"); 
echo $mysqli->affected_rows;



回答4:


change

$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");

to

$res2 = mysqli_query("INSERT INTO Table (name, value) VALUES ('$name', '$value')");


来源:https://stackoverflow.com/questions/19590078/how-to-get-affected-rows-using-mysqli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!