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

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条)

报告相同问题?

悬赏问题

  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊