如何将mysql数组转换为php数组

如何将mysql数组转换为php数组

问题描述:

        $cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' 
        and  status='1' ORDER BY RAND()");
       while($sd= $cg->fetch_assoc()){
       $title= $sd['title'];

        }

What i want to do is turn var $title to something like

     $mytitle[1] = 'first title';

     $mytitle[2] = 'second title';

     $mytitle[3] = 'third title';
      $randnews= rand(1, 3);
      echo $mytitle[$randnews];

Try this,I have tried based on my database table query, It's working as you expected.

Code:-

<?php
     require_once("connect.php");
     $sql=("SELECT * FROM news WHERE id='$postid' and status='1' ORDER BY RAND()");
     $result = $con->query($sql); 
     while($row = $result->fetch_assoc()){
      $array[] = $row['title'];      
      }
     echo "After Sorting".'<pre>';
     print_r($array);
     echo '</pre>';     
?>

$con is variable of connection class.

$con=mysqli_connect($servername,$username,$password,$my_db);

Output:-

[xyz] => "test"
[abc] => "tester"
[pqr] => "user"
[res] => "test"

Hope this helps

You should use fetch_all()

$cg = $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
$mytitle = $cg->fetch_all(MYSQLI_ASSOC);
$randnews = rand(1, 3);
echo $mytitle[$randnews]['title'];

$cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
       while($sd= $cg->fetch_assoc()){
       $title[]= $sd['title'];
        }

print_r($title);

try this..

 $cg= $mysqli->query("SELECT * FROM news WHERE id='$postid' and  status='1' ORDER BY RAND()");
           while($sd= $cg->fetch_assoc()){
           $title[]= $sd['title'];
            }
    echo $title[1]['col1'];
    echo $title[3]['col2'];

and HERE is the complete reference..

$title = array();
while($sd= $cg->fetch_assoc()){
   $title[] = $sd['title'];
}
your can user print_r($title) to check how the array looks 
it will look like 
Array(
  0 =>'first title',
  1 =>'second title',
  2 =>'third title'
)

A PHP array always start with 0 as a key and not 1. So if array length is 3 , the keys are 0 1 2 and so use rand(0,2) ie. rand(0,count($tile)-1)