mysql_query 返回 0 元素

标签 mysql foreach

我有这段代码,可以从 MySql 表中获取所有记录并执行切换状态:

<?php

$DB_host = 'localhost';
$DB_user = 'user';
$DB_password = 'pwf';
$DB_name = 'dbname';
$connessione = mysql_connect($DB_host, $DB_user, $DB_password);
$db_obj = mysql_query("SELECT * FROM `dbname`.`table`")or die("Query not valid: " . mysql_error());
$i = 0;
foreach ($db_obj as $dato) {
    $i++;
    switch ($dato->turno) {
        case 0:
            $desc = 'Mattina';
            $col = 'bg-color-redLight';
            break;
        case 1:
            $desc = 'Pomeriggio';
            $col = 'bg-color-greenLight';
            break;
        case 2:
            $desc = 'Notte';
            $col = 'bg-color-blueLight';
            break;
        case 3:
            $desc = 'Smonto Notte';
            $col = 'bg-color-yellow';
            break;
        case 4:
            $desc = 'Riposo';
            $col = 'bg-color-orange';
            break;
    }
}
?>

为什么结果 $db_obj 为空?表中有3条记录.. 你能帮我吗?

最佳答案

您没有将结果存储在任何合适的位置。看看mysql_fetch_array

$db_obj = mysql_query("SELECT * FROM `dbname`.`table`")or die("Query not valid: " . mysql_error());
$i = 0;
while($datato = mysql_fetch_array($db_obj, MYSQL_ASSOC)) { 
  $i++;
  switch ($dato['turno']) { 
      //Cases
  }
}

mysql_ 已弃用,建议查看 mysqlipdo

WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_fetch_array() PDOStatement::fetch()

关于mysql_query 返回 0 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087275/

相关文章:

javascript - .splice() 从数组中移除 2 个对象而不是 1 个

php - 在 foreach 循环参数中分解数组

php - 如何在 php 中将 mysql 数据库表中的值设置为 html 表单的隐藏输入

java - 为什么 Java 编译器会提示将 foreach 与原始类型一起使用?

php - 使用 PHP 的模数每 n 次迭代转储数据集

mysql - 如何从mysql中具有相同别名的两个或多个表中选择数据

c# - 列表和 foreach

带有从数组中提取的变量的 mysql_real_escape_string

php - 左连接 2 个表时如何减少 MySQL 上的用户优先级字段?

javascript - 将 Rest API 连接到 Google Charts