简体   繁体   English

MySQL查询返回对象,但我需要字符串

[英]mysql query returns object but I need String

I have a website with a form. 我有一个带有表格的网站。 The user first inputs a name and email into the database (I've got this working) and then he can input a name to search in the database and get a photo with the email. 用户首先在数据库中输入一个名称和电子邮件(我已经完成了工作),然后他可以输入名称以在数据库中搜索并通过电子邮件获取照片。 I've got the $return value but it is an Object, and in the image creation method I need it to be a String. 我有$ return值,但它是一个对象,在图像创建方法中,我需要将其作为字符串。 I've tried to convert it with a cast but it doesn't work. 我试图用演员表将其转换,但是它不起作用。 (I've tried outputing it first) (我尝试过先输出)

Here's the HTML: 这是HTML:

<form name="getEmail"
action="getEmail.php"
method="GET">
Name: <input type="text" name="getEmail" id="getEmail" value="Email..." maxlength="100"         size="20" onclick="this.value=''" />

Here's the PHP: 这是PHP:

<?php
$con=mysqli_connect("localhost","root","","assignment1");

if (mysqli_connect_errno()) {
echo "Could not connect to the mySQL database: " . mysqli_connect_error();
}



// create a 100*30 image
$im = imagecreate(100, 30);

// white background and blue text
$bg = imagecolorallocate($im, 120, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

$name=$_GET['getEmail'];
$result = mysqli_query($con,"SELECT email FROM Users WHERE name='$name' ");


echo (String)$result;
// write the string at the top left
imagestring($im, 5, 0, 0,$result, $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);


mysqli_close($con);
?>

You have not fetched your result that's why you are getting a mysqli_result object .Use mysqli_fetch_assoc() to mysqli_fetch_array() : 您尚未获取结果,这就是为什么要获取mysqli_result对象的原因。对mysqli_fetch_assoc()使用mysqli_fetch_array()

$result = mysqli_query($con,"SELECT email FROM Users WHERE name='$name' ");
while ($row = mysqli_fetch_array($result))
      echo $row['email'];

Use this: 用这个:

$q = mysqli_query($con,"SELECT *
FROM Users WHERE
name='$name' ");

$ar = mysqli_fetch_assoc($q);
$result = $ar['email'];

echo $result;

When you use: 使用时:

$result = mysqli_query
($con,"SELECT email
FROM Users WHERE
name='$name' ");
echo (String)$result;

You aren't actually selecting the value of the 'email' column for that row, but the full object. 您实际上不是为该行选择“电子邮件”列的值,而是完整的对象。 What you want to do is select everything from the row, and form an array from this. 您要做的是从该行中选择所有内容,然后从中形成一个数组。 That way you can then select the 'email' value from this array. 这样,您就可以从该数组中选择“电子邮件”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM