Imploding to mysqli_fetch_array() - php

Im new to web development.
I need the array like following
["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
I tried. But I failed.I connected the database. How can I make it?
my array-code
$count=0;
$sql="SELECT name FROM planet";
$sql_run=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($sql_run))
{
$result[] = "'".implode("\'",$row)."'".",";
echo $result[$count++];
}
By using above code, i couldn't get the result what I expected.

Each fetch returns one planet in associative array. To get array of rows, you have to do:
$list = array();
while($row = mysqli_fetch_assoc($sql_run)) {
array_push($list, $row['name']);
}
var_dump($list);

Related

PHP array_push overwriting the pushed data

I seeing a rare behavior of the array_push php function. It's like when I'm looping through the result rows of the query and pushing the complete array of data into a 'parent' array ($rdo), the values are beeing modified with the ones of the last row added.
This is my code:
$rdo = array();
if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
$sentencia->execute();
$sentencia->store_result();
$num_of_rows = $sentencia->num_rows;
$sentencia->bind_result($row['monthly_price'], $row['name']);
while($sentencia->fetch())
{
array_push($rdo, $row);
echo print_r($rdo,1).'<br/><br/>';
}
$sentencia->close();
die();
}
And this is the result:
It looks like this is an artifact of the way bind_result() uses references to the array elements. When you push $row onto $rdo, this is updating all those array elements.
I recommend you move away from using bind_result() and use fetch_assoc().
if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
$sentencia->execute();
$result = $sentencia->get_result();
while($row = $result->fetch_assoc())
{
array_push($rdo, $row);
echo print_r($rdo,1).'<br/><br/>';
}
$sentencia->close();
die();
}

Array push rows from SQL query

I am trying to save the rows (results) from an SQL query to a csv file.
I am using array push in order to put the results in a list. Later I put the data from this list to my csv file.
My code :
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list, $row['campaign']);
}
The results are there because sprintf works. The problem is with the syntax of array_push. I even tried :
array_push($list, array(''.$row['campaign']);
I am getting an error:
fputcsv() expects parameter 2 to be array
The full code is here :
$list = array
(
array('old_campaign_name', 'new_campaign_name')
);
// table 1
$sql = ('select distinct(campaign) as campaign from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list,$row['campaign'],'');
}
$fp = fopen($location, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
As the error says, fputcsv expects each row that you put to be an array, so it can write it out with commas separating the elements. $list should be a 2-dimensional array, so you need to push an array onto it when you're building it.
while ($row = $query->fetch_assoc() {
$list[] = array($row['campaign']);
}
BTW, $list[] = x is equivalent to array_push($list, x).
When you initially create the $list array, it is an array containing one array. But when you add more values to it from your query results, you are pushing strings onto the end of it, not arrays. In effect, you will be making something like
$list = array (
array('old_campaign_name', 'new_campaign_name'),
'first campaign',
'second campaign',
'etc.',
...
);
Because of this, when you loop over $list, the first value should work with fputcsv, because it is an array, but any subsequent values will be strings instead of arrays and will cause the error you are seeing.
You should be able to fill the $list like this:
while ($row = $query->fetch_assoc()) {
$list[] = $row;
}
$list[] = $row will not overwrite the values previously in $list. From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
It works like this :
while ($row = $query->fetch_assoc())
{
// array_push($list,$row['campaign'],'');
array_push($list,array($row['campaign'], ''));
}

php mysql_fetch_array() not working as expected

$result = mysql_query($strSql);
foreach($bestmatch_array as $restaurant)
{
while($row = mysql_fetch_array($result))
{
if($restaurant == $row[0])
{
$value = $row[1];
}
}
}
What I am trying to do is sort the result of array formed by query according to the values stored in $bestmatch array.
I don't know what I am doing wrong but the 4th line just seems to run once. Please help guys. Thanx in advance.
php mysql_fetch_array() not working as expected
Your expectation is not right.
foreach($bestmatch_array as $restaurant)
{
// This loop will only run for first iteration of your foreach.
while($row = mysql_fetch_array($result))
{
}
// everything has been fetched by now.
}
That is a logically incorrect sequence.
You expect your inner loop to be called over and over again as many times as you have the outer loop run but record fetch does not work like that. For outer loop's first run all the rows in $result will be fetched and since you do not reset the counter after your while loop that means after the first run there will be no more rows for the next run.
Solution? Fetch the row from mysql first then use a simple in_array call to check whether that restaurant is there in your array.
$result = mysql_query($strSql);
while($row = mysql_fetch_array($result))
{
$name=$row[0];
if(in_array($name,$bestmatch_array))
$value=$name;
}
Store the results of the query in the array first:
$result = mysql_query($strSql);
$results_row = array();
while($row = mysql_fetch_array($result))
{
$results_row[] = array($row[0],$row[1]);
}
foreach($bestmatch_array as $restaurant)
{
foreach ($results_row as $key => $value)
{
if($restaurant == $results_row[$key][0])
{
$value = $results_row[$key][1];
}
}
}

How do you save ALL ROWS of ODBC result to array in PHP?

I can't seem to find a way to save all rows from odbc_exec to an array. I found php_fetch_array, but that only fetches one row at a time, requiring me to iterate through all rows to put it into an array. Is there a more concise way to do this?
Tried
`
$myArray = array();
while (odbc_fetch_row($result)) {
$myArray[odbc_result($result,1)] = odbc_result($result,2);
}`
and also
`
$myArray = array();
while ($myRow = odbc_fetch_row($result)) {
$myArray[$myRow['id']] = $myRow['name'];
}`
but $myArray is still empty.

json showing duplicate output of mysql result

I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:
[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]
The code behind this is:
$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
Any idea?
This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.
Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().
while($r = mysql_fetch_assoc($result)) {
$dataArray[] = $r;
}
You should set another fetch style. It now fetches all columns using both their 0 based index and their name.
This should work as expected:
$dataArray = array();
while($r = mysql_fetch_array($result, MYSQL_ASSOC))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
You're getting this because you can access the results either by name or by column index, but you're serializing the entire thing, so both ways of getting the data are showing up.
try this
//$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
I commented first line. Because you used like that $dataArray[].

Categories