doucang6739 2014-09-01 02:28
浏览 90
已采纳

PHP / MySQL:使用MySQL Query中的数组元素声明变量

I am trying to retrieve data from my database and assign the array elements to PHP variables that I wish to use throughout my program so that I don't have to worry about posting separate form data later on.

I know the query I currently have set up is currently working from previous tests but when I try to use a FOR loop to output variables I've assigned from the MySQL query result, only the first element from the database is displayed.

PHP/MySQL Code:

// Retrieve tasks from the tasks table 
$tasks_sql = "SELECT DISTINCT taskname FROM tasks";
$tasks_result = mysqli_query($usermysqli, $tasks_sql);
if (! $tasks_result){
      die('Could not retrieve data: ' . mysql.error());
    }

// Array for assigning tasknames to global variables

while($tasks_displayed = $tasks_result->fetch_array()) {

for ($i=0, $inputlen = count($tasks_displayed); $i < $inputlen; $i++) {
${'line'.($i+1)} = $tasks_displayed[$i];
}

}   

// Test to see if the array above actually worked.
echo "Task 1 from array: " . $line1 . "<br>";
echo "Task 2 from array: " . $line2 . "<br>";
echo "Task 3 from array: " . $line3 . "<br>";
echo "Task 4 from array: " . $line4 . "<br>";
echo "Task 5 from array: " . $line5 . "<br>";
echo "Task 6 from array: " . $line6 . "<br>";

Only the first element is displayed properly and variables $line2 - $line6 are currently null. Is this a simple coding error?

  • 写回答

3条回答 默认 最新

  • doucheng5209 2014-09-01 02:51
    关注

    Since your for loop is nested inside your while fetch loop and you are using the for loop to populate individual variables, on each loop iteration you are overwriting the same variable. In other words, on every fetch, you get back an array of 1 row having 1 element. The for loop then goes over that single row and populates only the first variable, again and again.

    The for loop needs to happen after the while loop, once all rows have been fetched into an array.

    // Fetch an associative array
    // array to hold all tasks
    $tasks = array();
    // Also, consider sticking with the procedural method since that's what you use elsewhere
    while ($tasks_displayed = $tasks_result->fetch_assoc()) {
    // procedural alternate:
    // while ($tasks_displayed = mysqli_fetch_assoc($tasks_result)) {
      // Append the task onto your array
      $tasks[] = $tasks_displayed['taskname'];
    }
    // Following the loop you now have an array of tasks.
    // you can use a for loop to display them:
    $tasklength = count($tasks);
    for ($i = 0; $i < $tasks; $i++) {
      // Populate your variables...
      ${'line'.($i+1)} = $tasks[$i];
    }
    

    But...

    That said, an incrementing for loop is really uncommonly used in PHP. foreach is almost always p preferred. If you really must populate these local variables instead of just using them directly from the $tasks array we populated earlier, use a foreach:

    foreach ($tasks as $key => $task) {
        ${'line'.($key + 1)} = $tasks[$key];
    }
    

    Really, the most conventional thing to do here would just be to keep the tasks in the $tasks array created inside the while loop instead of populating a potentially unknown number of variables, adding them to the local or global symbol table unnecessarily. If the tasks are related (they arguably are, simply since they are all tasks), then it is wise to keep them bound together in an array.

    // Use $tasks as an array, don't populate variables:
    foreach ($tasks as $key => $task) {
      echo "Task $key from array: $task<br/>
    "; 
    }
    

    As noted in comments, watch out for mixing up mysql_*() with the mysqli_*() APIs. Your call to mysql_error() should be instead a call to mysqli_error($usermysqli)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀