Mysql select single column as single dimensional array in PHP

I select one column from my mysql database:

$savedSQL = 'SELECT can_id FROM savedsearches WHERE user_id = "'.mysql_real_escape_string($user_id).'" AND insertTime >= "'.$lastSigTime.'"'; $savedQuery = mysql_query($savedSQL); 

And I would like to return the values ​​as a single dimension, an enumerable array, such as array [0] = row1, array [1] = row2, etc.

When I put it in an array like this:

 while($savedResult = mysql_fetch_array($savedQuery)) { $savedArray[] = $savedResult; } 

It returns it as a multidimensional array, so that the array [0] [0] = row1, array [1] [0] = row2, etc.

I was thinking of adding something like this:

 while($i=0;$i<count($savedArray);$i++) { $newSavedArray[$i] = $savedArray[$i][0] } 

But is there an easier and more efficient way to do this?

+4
source share
5 answers

You are very close. You just need to access $savedResult[0] to get your column, and add it to $savedArray

 while($savedResult = mysql_fetch_array($savedQuery)) { $savedArray[] = $savedResult[0]; } 
+10
source
 while($savedResult = mysql_fetch_array($savedQuery)) { $savedArray[] = $savedResult['can_id']; } 
+2
source

to try

 $savedArray[] = $savedResult['can_id']; 

instead

 $savedArray[] = $savedResult; 
+1
source

The method used here is with mysqli and no loop. It takes all your code up to two lines.

 $r = mysqli_query($c,'SELECT can_id FROM savedsearches WHERE user_id = "'.mysql_real_escape_string($user_id).'" AND insertTime >= "'.$lastSigTime.'"'); $savedArray = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"can_id"); 
+1
source

When you initially get mysql results, you can combine the contents of both while loops into one:

 while($result = mysql_fetch_array($savedQuery)) { $savedArray[] = $result[0]; // or $result['can_id'] } 
0
source

Source: https://habr.com/ru/post/1382172/


All Articles