Return MySQL rows in array - php

I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.

$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);

Related

How to using implode from looping table in PHP?

I get error
Array to string conversion
when to implode looping from table
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
//This is I'm get data from other database server(SQL server) where in 'id' from database test(local database)
//and result query i will save to table test3(database server local)
$query = $db2->query("SELECT * FROM test2 WHERE id IN($val)");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);
How can I fix it?
i get error
Error Number: 37000
[Microsoft][ODBC SQL Server Driver][SQL Server]Error converting data type varchar to numeric.
SELECT * FROM test3 WHERE id IN(1,2,3,4)
Filename: D:/xampp/htdocs/sipdn/system/database/DB_driver.php
Line Number: 691
I think you are not seeing that when you do this:
$array[] = array('id' => $row->id);
You are assigning an array, inside another array, and the implode function is expecting an array of values, and not an array of array with values.
The answer is that you should do this
foreach ($sql->result() AS $row){
$array = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
Instead of this
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
$implode = IMPLODE(',',$array);
}
And the reason is that implode function firm is
string implode ( string $glue , array $strings )
Hope it helps!
try this, the simple code without implode and array
$sql = $this->db->query('select * from TEST');
$val = '';
foreach ($sql->result() AS $row){
$val .= $row->id.',';
}
// before rtrim $val is 1,2,3,
$val = rtrim($val,',');
// after rtrim $val is 1,2,3
$query = $this->db->query("SELECT * FROM TEST WHERE id IN('".$val."')");
// finally query will be "SELECT * FROM TEST WHERE id IN('1,2,3')"
may it can help you
You are setting an array inside an array. $array[] = means create a new key in $array and put everything after the equal sign into that key. So you don't have to create a new array.
It is simple as this $array[] = $row->id.
Then $array[0] would be the first id that is in the database and so on.
The problem solved I'm using query like bellow. Thanks all for response.
$sql = $this->db->query('select * from TEST');
foreach ($sql->result() AS $row){
$array[] = array('id' => $row->id);
}
$query = $db2->query("SELECT * FROM mCIF WHERE nocif IN ('".implode("','",$array)."')");
$result = array();
foreach($query->result_array() AS $row){
$result[] = array (
'id' => $row['id'],
'nm' => $row['nm'],
'golcust' => $row['golcust'],
'golcustbi' => $row['golcustbi'],
'jnsbh' => $row['jnsbh']
);
}
$this->db->insert_batch('test3',$result);

How to return an entire column as an array using PHP

I am trying to fetch a column from a database and display the entire contents as an array. I have so far been able to fetch only one of the entries from the table. I understand that I am fetching only $row[0] which is why i am getting only 1 element. I have tried to fetch all elements but I have not succeeded yet. can someone please let me know how to do it correctly? I have attached my code below.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT `current` FROM `monitor` ORDER BY `Sno.`";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_NUM);
printf("%s\n",$row[0]);
mysqli_close($con)
?>
PDO has a dedicated feature for your problem PDOStatement::fetchColumn.
So, from your question what I understand is- you want to fetch a database column and store this in a array which will make you to display the results.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT current FROM monitor ORDER BY Sno";
$result = mysqli_query($con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
$first_col = array_column($arr, 0);
print_r($first_col);
mysqli_close($con)
?>
i.e. if you have five entry to the database whose first column contains
the values like 'current1', 'current2', 'current3', 'current3' and 'current4' the result of this code will be
Array
(
[0] => current1
[1] => current2
[2] => current3
[3] => current4
[4] => current5
)

PHP multidimensional to flat array (changing key->value)

This is a problem that I come across frequently when using PHP to query mysql data, and I would like to know if there is a more efficient solution. When I only need two columns of data, for instance the columns 'id' and 'price', I prefer this 'flat' format:
array(
id 1 => price 1,
id 2 => price 2,
id 3 => price 3,
...
);
or in json:
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
And my usual solution is to loop twice, like so:
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id' => $row['id'],
'price' => $row['price']
);
}
mysql_close($con);
$array2 = array();
foreach ($array1 as $key => $value) {
$array2[$key][$value['id']] = $value['price'];
}
print json_encode($array2);
which does work, but I think this code is too lengthy for its purpose, and there should be a better way -- so that I only have to loop one array. Any suggestions?
You can simplify your loop to this
while ($row = mysql_fetch_assoc($info)) {
$array1[] = array(
'id '.$row['id'] => 'price '.$row['price']
);
}
print json_encode($array1);
$result = array();
while ($row = mysql_fetch_assoc($info)) {
$result[$row['id']] = $row['price'];
}
print_r($result);
require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");
$array1 = array();
while ($row = mysql_fetch_assoc($info))
$array1[$row['id']] = $row['price'];
mysql_close($con);
print json_encode($array1);
NOTE: your $array2 is a two dimensional array. If it works for you, you need to change your javascript code to handle following flat format i.e. the above code produce
[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]

Create dynamic associated array from database fields

I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...

Adding to a multidimensional array in PHP

I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}
You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.
You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.
Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}

Categories