mysqli语句在php

时间:2016-04-21 04:31:31

标签: php mysql mysqli

mysqli select语句有点问题,因为我做了一个实际计算结果数的select语句。但它不返回我想要的值,而是返回none。需要帮助的人。我使用mysqli和php

将这个select语句作为函数
function count_result($data){
    global $con;
    $sql    = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
    $result = mysqli_query($con,$sql) or die('userssss');
    echo "string</br>";
    $row    = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
    echo $row['userssss']."asdasd</br>";
    die("userssss");
    $return = $row['user'];

    return $return;
}

结果

的字符串
asdasd
userssss

它应该在asdasd

之前显示结果

4 个答案:

答案 0 :(得分:0)

添加全局$ con;

function count_result($data){
    global $con;
    $sql    = "SELECT count(user_id) as user from credentials where user_id = '$data'";
    $result = mysqli_query($con,$sql);
    $row    = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
    echo $row['user'][0]."asdasd";
    die();
    $return = $row['user'][0];

    return $return;
}

答案 1 :(得分:0)

我找到了。我很傻。

不必使用assoc,而是必须使用数组

function count_result($data){
    global $con;
    $sql    = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
    $result = mysqli_query($con,$sql) or die('userssss');
    $row    = mysqli_fetch_array($result,MYSQLI_ASSOC);
    $return = $row['user'];

    return $return;
}

答案 2 :(得分:0)

代码中的一个愚蠢的错误:

function count_result($data){
    global $con;
    $sql    = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
    $result = mysqli_query($con,$sql) or die('userssss');
    echo "string</br>";
    $row    = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
    echo $row['user']."asdasd</br>"; // did changes on this line 
    die("userssss");
    $return = $row['user'];

    return $return;
}

答案 3 :(得分:0)

你需要计算所有含义匹配where子句的行。也尝试采用准备好的陈述。 Bellow代码有效。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function count_result($data){
$user = 'username';
$password = 'password';
$db = 'database';
$host = 'hostname';
$port = 3306;

/* Attempt MySQL server connection. Assuming you are running MySQL server */

$link = mysqli_connect($host, $user, $password, $db);

// Check connection
if($link === false){
   die("ERROR: Could not connect. " . mysqli_connect_error());
}

if($stmt = $link -> prepare("SELECT COUNT(*) FROM test WHERE ID= ?")) 
    {
    /* Bind parameters, s - string, b - blob, i - int, etc */
    $stmt -> bind_param("i", $data);
    $stmt -> execute();

    /* Bind results */
    $stmt -> bind_result($testfield1);

    /* Fetch the value */
    $stmt -> fetch();
    $numberofrows = $stmt->num_rows;

} else{
    echo "ERROR: Could not able to execute SQL. " . mysqli_error($link);
}

/* Close statement */
$stmt -> close();
echo '# rows: '. $numberofrows . PHP_EOL;
echo 'Count = '. $testfield1 ;

}

count_result(24);
?>