How to using implode from looping table in PHP? - 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);

Related

PHP SQL statement using REGEXP to fetch multiple values

How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"

PHP change array values to create new array

this way how i get array from db:
$sql = "SELECT * FROM table_name";
$query = mysqli_query($conn, $sql);
$db_array = array();
// start fetch for words
if (mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
$db_array[] = $row;
}
}
My array looked like this:
Array
(
[cat cute] => animal#cute animal
[cat women] => film
)
How to add '{' and '}' to all values?
I wish i can get new array like this:
Array
(
[cat cute] => {animal#cute animal}
[cat women] => {film}
)
It's hard for me, i am new in php development.
Try this,
$arr = array
(
'cat cute' => 'animal#cute animal',
'cat women' => 'film'
);
array_walk($arr, function(&$item){
$item = '{'.$item.'}';
});
print_r($arr);
Here is the link for array_walk()
Since you want a new array, try this:
<?php
array_map(function($value)
{
return '{' . $value . '}';
}, $arr);
array_walk() in rahul_m's answer modifies your array, while array_map() creates a new one.

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"}, ...]

Return MySQL rows in array

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
);

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