MYSQL获取列值并在PHP中显示

时间:2019-05-21 15:10:34

标签: php mysql

我有问题

我要回显“点”列的值

我尝试了什么,但是没有用:

$stmt = $mysqli->prepare("SELECT points FROM member_profile WHERE user_id = '$firstName'");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
    $array[] = $row['points'];
}
print_r($array);

这是我当前的代码:

<?php
header('Content-Type: text/html; charset=Windows-1250');    
session_start();
$firstName = $_SESSION['firstname'];

$servername = "db.xxxx.gsp-europe.net";
$username = "xxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxx";

/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection   

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
        $rows = mysqli_num_rows($result);
        //if exist increse points with 1
        if($rows>=1){

$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";

   if ($conn->query($sql) === TRUE) {
    echo "Thingz created successfully";
} else {
    echo "Error doing sum thingz: " . $conn->error;
}
        }
        //if don't exist create user with points 0
        if($rows==0)
        {
            $query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";

            $result = mysqli_query($conn,$query)or die(mysqli_error($conn));


$conn->close();

        }





?>

简而言之,我需要的是:在文件末尾,将是一个“ echo”,它将显示带有标识符“ user_id”的“ points”列的当前值。就这样

感谢您的宝贵时间,谢谢!

1 个答案:

答案 0 :(得分:1)

您正在获取结果,但未获取数据。

$stmt->get_result()返回结果集-> mysqli_result,要处理此结果,您需要从该结果中调用方法fetch_array()

将代码更改为:

$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
    $array[] = $row['points'];
}

如果您只想要1个结果而不使用数组,请不要使用数组(是,是)。

$results = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
    $points = $row['points'];
}