PHP MySQL混乱

时间:2012-10-07 00:44:28

标签: php mysql

我是PHP的新手,并不了解与mysql的交互,特别是在运行后的查询。这是我的代码:

$mysqli = new mysqli('localhost', 'foo', 'bar', 'table');
    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
    }

    $sql = "select column_name from information_schema.columns where table_name='activity'";
    if ($execute = $mysqli->query($sql)) {
        $result = mysqli_fetch_array($execute);//trying an array
        $row_count = count($result);
    }
    for ($i=0; $i < $row_count; $i++) { 
        echo $i . ' ' . $result['column_name'] . '<br>';
    }

当我像这样运行时,我得到了这个输出:

0 i
1 d

跆拳道?
当我在数据库上运行相同的查询时,我得到了这个:

column_name
___________
id
name
description
score
quality_id
date_mod

这正是我想要的,但在php中 我也试过这个:

for ($i=0; $i < $row_count; $i++) { 
    echo mysql_result($execute, $i, 'column_name');
}

我得到了

  

mysql_result()期望参数1为资源

我没有到达什么地方?

有没有办法让数据库互动更容易?

2 个答案:

答案 0 :(得分:2)

mysqli_fetch_array的调用会将结果集的第一行作为数组提供给你,它不会在数组中给出所有结果。

如果您想获得所有结果,则必须执行以下操作:

$i = 0;
While ($result = mysqli_fetch_array($execute))
{
  echo $i . ' ' . $result['column_name'] . '<br>';
  $i++;
}

顺便问一下,你确定要回复$result['column_name']吗?从结果中可以看出,您使用的是$result[$i]

答案 1 :(得分:0)

乍一看,我看到

if ($execute = $mysqli->query($sql)) {

$ execute未定义,您应该使用==进行比较

$mysqli = new mysqli('localhost', 'foo', 'bar', 'table');
    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
    }

    $sql = "select column_name from information_schema.columns where table_name='activity'";

    /**
     * Execute the query. Returns false on failure.
     * On success, returns an an object (we store that object in $result)
     * in which you can do things like fetch_array(), etc
     */
    $result = $mysqli->query($sql);

        /**
         * in here you can pass MYSQLI_NUM, MYSQLI_ASSOC, MYSQLI_BOTH
         * MYSQLI_NUM will allow you to do echo $row[0];
         * MYSQLI_ASSOC will allow you to do echo $row['column_name'];
         * MYSQLI_BOTH will let you do both.
         */

        // Store results in the $row array
        $rows = $result->fetch_array(MYSQLI_ASSOC) // in here you can pass MYSQLI_NUM, MYSQL_ASSOC or MYSQL_BOTH
        $row_count = count($rows);
    }
    for ($i=0; $i < $row_count; $i++) { 
        echo $i . ' ' . $row['column_name'] . '<br>';
}