php 注意:数组到字符串的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11596693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:50:11  来源:igfitidea点击:

Notice: Array to string conversion in

phpmysqlsql-serverarraysselect

提问by Sunden

I'm trying to select a value from a database and display it to the user using SELECT. However I keep getting this error:

我正在尝试从数据库中选择一个值并使用 SELECT 将其显示给用户。但是我不断收到此错误:

Notice: Array to string conversion in (pathname) on line 36.

I thought that the @mysql_fetch_assoc();would fix this but I still get the notice. This is the part of the code where I'm getting the error:

我以为@mysql_fetch_assoc();会解决这个问题,但我仍然收到通知。这是我收到错误的代码部分:

  {
  $loggedin = 1;

  $get = @mysql_query("SELECT money FROM players WHERE username = 
 '$_SESSION[username]'");
  $money = @mysql_fetch_assoc($get);

  echo '<p id= "status">'.$_SESSION['username'].'<br>
  Money: '.$money.'.
  </p>';
  }

What am I doing wrong? I'm pretty new to PHP.

我究竟做错了什么?我对 PHP 很陌生。

采纳答案by Razvan

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:

问题在于 $money 是一个数组,您将其视为字符串或可以轻松转换为字符串的变量。你应该这样说:

 '.... Money:'.$money['money']

回答by user1046243

Even simpler:

更简单:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around usernamein the $_SESSIONreference.

注意周围的引号的用户名$ _SESSION参考。

回答by Learner

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

mysql_fetch_assoc 返回一个数组,所以你不能回显一个数组,需要 print_r() 否则特定的字符串 $money['money']。

回答by Learner

You cannot echo an array. Must use print_r instead.

您不能回显数组。必须改用 print_r。

<?php
$result = $conn->query("Select * from tbl");
$row = $result->fetch_assoc();
print_r ($row);
?>

回答by Ernesto Jr Montejo

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.

您将收到此通知的原因之一:数组到字符串的转换在...中是您正在组合一组数组。例如,整理出几个名字和姓氏。

To echo elements of array properly, you can use the function, implode(separator, array)Example:

要正确回显数组元素,您可以使用该函数,implode(separator, array)例如:

implode(' ', $var)

result:

结果:

first name[1], last name[1]
first name[2], last name[2]

More examples from W3C.

来自W3C 的更多示例。

回答by user5336032

Store the Value of $_SESSION['username'] into a variable such as $username

将 $_SESSION['username'] 的值存储到一个变量中,例如 $username

$username=$_SESSION['username'];

$get = @mysql_query("SELECT money FROM players WHERE username = 
 '$username'");

it should work!

它应该工作!