php,MySQL:如何显示SELECT COUNT WHERE结果?

时间:2019-02-20 09:53:58

标签: php mysql

我想显示带有'WHERE'子句的'SELECT COUNT'的结果,我不知道这是否是语法问题;这是我的代码:

$sql="SELECT COUNT(*) FROM utenti WHERE surname= 'Smith'";
$rs = $conn->query($sql);
$result = mysql_fetch_array($rs);
echo $result[0];

2 个答案:

答案 0 :(得分:0)

您正在尝试使用不推荐使用的API MySQLi http://php.net/manual/en/book.mysqli.php

尝试使用PDO代替https://www.w3schools.com/php/php_mysql_connect.asp

$sql = "SELECT count(*) FROM utenti WHERE cognome = 'Tosone'"; 
$result = $con->prepare($sql); 
$result->execute(); 
$number_of_rows = $result->fetchColumn(); 

答案 1 :(得分:0)

尝试一下:

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT count(*) AS nb FROM utenti WHERE surname= 'Smith'")) {
    $res = $result->fetch_assoc();

    print_r($res["nb"]);

    /* free result set */
    $result->close();
}