doumigu9594 2018-10-14 14:06
浏览 650
已采纳

PHP / MYSQL错误:类mysqli_result的对象无法转换为字符串

I've just started learning about mySQL together with PHP(basics), and I am stuck for 2 days now with this error. I have HTML code :

<html>
<head>
    <title>Title</title>
</head>
<body>
    <?php include 'pehape.php' ?>
<span>Username:</span><?php echo $var ?>
</body>
</html>

I am just trying to get the name of an user from database using this code:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";



$conn = new mysqli($servername, $username, $password, $dbname);

$var = $conn->query("SELECT Name FROM users WHERE ID=0");

?>

This is what I get as a result in web browser.

Username:
Recoverable fatal error: Object of class mysqli_result could not be converted to string in /storage/ssd3/749/7441749/public_html/index.php on line 7

Now after the result that I am getting is Object but I don't know how to convert it to string using PHP. -Does anyone know how to fix this?To convert Object to string.

I have tried using print_r function and it didn't work out for me.I found very little information about this.Also, this is my database structure if you need it for some information( I guess that might have impact, don't know) : http://prntscr.com/l5xu9n

  • 写回答

2条回答 默认 最新

  • dtpn60029 2018-10-14 14:13
    关注

    $var in your code is actually an object of type mysqli_result.

    This is actually a handle to a resultset, and you have to unload the results from that handle using some sort of fetch.

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // dont normally get ID's of zero so I chnaged this to 1
    $result = $conn->query("SELECT Name FROM users WHERE ID=1");
    
    // now get the result row
    $row = $result->fetch_assoc();     // row will be an array
    
    ?>
    

    Now in your HTML you can do this

    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <?php include 'pehape.php' ?>
    <span>Username:</span><?php echo $row['Name'];?>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的