如何在PHP中显示多个数组值?

时间:2016-06-29 12:43:00

标签: php mysql

我在PHP中显示值时遇到了麻烦。

值传递到网址career.php?mode=1,2,3

这是我的代码

$id = $_GET['mode']; // Id get from URL
    //echo $id;
    $query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";
    $res    = mysqli_query($conn, $query);

    foreach(($row = mysqli_fetch_array($res)) as $key1){
          $key[] = $key1;
    }

PHP代码:

<?php echo $key;?>

因此它处于循环中,因此它显示了最后一个循环值。是否可以通过循环显示所有值。

帮帮我们!!

5 个答案:

答案 0 :(得分:1)

您有多个输出数组的选项。

Echo和foreach

您循环浏览数组并回显每个$key$value

foreach ($keys as $key => $value) {
    echo $key." : ".$value."<br />";
}

print_r和var_dump

这主要用于调试。

print_r($keys);

var_dump($keys);

内爆

您可以内爆数组以回显连接的值。

// The first parameter is the devider or separator
echo implode('', $keys);

是否可以在列中显示多个值?

是的,当然。请看以下示例:

foreach ($keys as $value) {
    echo $value['columnone'];
    echo $value['columntwo'];
    echo $value['columnthree'];
}

资源

答案 1 :(得分:1)

由于你的代码处于open for sql注入状态,你需要使用bind and prepare语句。使用while循环将数据回显为

$ids[] = $_GET['mode']; // store it into array
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN (";
$query .= implode(',', array_fill(0, count($ids), '?'));// bind your param
$query .= ') ';
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $ids);//Call a callback with an array of parameters
$stmt->execute();
$stmt->bind_result($job_title);// bind result

while ($stmt->fetch()) {// use wlile loop here
    printf("%s\n", $job_title);//echo  result
}

答案 2 :(得分:0)

您可以这样做:

$mysqli = new mysqli("server", "user", "password", "db");
$id = $_GET['mode'];
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";    
if($res = $mysqli->query($query)){    
    while($obj = $result->fetch_object()){
        echo $obj->job_title;
    }
}
$res->close(); 

答案 3 :(得分:0)

试试这个:

<?
    $servername = "localhost";
    $username = "yourUSERNAME";
    $password = "yourPASS";
    $dbname = "yourDBNAME";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
         exit();}

        $id = $_GET['mode']; // Id get from URL
            //echo $id;
            $query = "SELECT `job_title` FROM `job` WHERE `job_id`=".$id."";
            $result = $conn->query($sql);
            while($row=$result->fetch_assoc()){ 
           //do something...
            }
     $conn ->close(); 
?>

提示:将您的连接放在另一个connection.php文件中。

喜欢:

require('Connect.php');

答案 4 :(得分:-1)

$cars = array
  (
  array("Volvo",22,18),

  array("BMW",15,13),

  array("Saab",5,2),

  array("Land Rover",17,15)

  );

for ($row = 0; $row < 4; $row++) {

  echo "<p><b>Row number $row</b></p>";

  echo "<ul>";

  for ($col = 0; $col < 3; $col++) {

    echo "<li>".$cars[$row][$col]."</li>";

  }

  echo "</ul>";

}