$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'blood_db';
$connection = new mysqli($dbhost,$dbuser,$dbpass,$db);
if($connection->connect_error){
die("Server Error ".$connection->connect_error);
}
else{
$query = ("SELECT first_name FROM accounts WHERE email_address = '".$_SESSION['username']."'");
$obj = $connection->query($query);
echo "Welcome ".$obj->first_name;
这里显示了一个通知,即" 注意:未定义的属性:mysqli_result :: $ first_name" 它正在返回对象,那么如何从中提取名字呢?
// printf("Welcome %s",$result->);
echo '<br><a href="logout.php">Logout</a>';
答案 0 :(得分:2)
使用下面的代码
$result = $connection->query($query);
if($result){
$row = $result->fetch_assoc();
echo "Welcome ".$row['first_name'];
}else{
// check error
}
答案 1 :(得分:2)
如果要检查数据是否为空,您可以尝试选择数据并添加条件
$obj = $connection->query($query);
if ($obj->num_rows > 0) {
$row = $obj->fetch_assoc();
echo "Welcome ".$row['first_name'];
}
如果您不想检查数据,请使用此
$row = $obj->fetch_assoc();
echo "Welcome ".$row['first_name'];
了解更多信息
答案 2 :(得分:1)
一个非常基本的例子是这样的:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$firstname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_test WHERE email_address = '". $_SESSION['username']. "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Retrieve Firstname
while($row = $result->fetch_assoc()) {
$firstname = $row["first_name"];
}
} else {
echo "No results found!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<header>
<h3>Welcome <?php echo $firstname; ?></h3>
</header>
</body>
</html>
<?php
$conn->close();
?>