String from Database into an Array - php

I have a field in my database which holds id's. An example would be: 1,2,3,4,5
I basically need to take that string and make it into 1 array so I can do a query with: WHERE id IN ($string_array).

PHP: explode - Manual
$string = "1,2,3,4,5";
$array = explode(",", $string);
$query = "SELECT * FROM `table` WHERE id IN (".$string.")";
$query = mysql_query($query);

I think this is what you're looking for:
$array = explode(",",$string)

Related

how to add apostrophe in string

I had a value like this $x = 'LA1,LA2,LA3,LA7';
And I want to this value to be execute in my sql.
I know it will return error because missing '' in each id's. example 'LA1','LA3','LA7'
How to add this symbol so query can execute? Any idea?
$sql = 'SELECT * FROM tbl WHERE id IN ("'.$x.'")';
Using a combination of explode and implode ought to work
$x = 'LA1,LA2,LA3,LA7';
$sql = sprintf('SELECT * FROM tbl WHERE id IN ("%s")', implode( '","', explode(',',$x) ) );
Ill suggest to put in array rather than keeping it in a string,
$variables = array('apple','orange','kiwi');
$variables = implode("','",$variables );
$sql = 'SELECT * FROM tbl WHERE id IN ('{$variables}')';
split it to array then add apostrophe
$x = 'LA1,LA2,LA3,LA7';
$arrayX = explode(',', $x);
$sql = 'SELECT * FROM tbl WHERE id IN ("'.implode('",', $arrayX).'")';
You need explode() and join()
$x = 'LA1,LA2,LA3,LA7';
$x = explode(",", $x);
$x= join("', '", $x);
$sql = "SELECT * FROM tbl WHERE id IN ('$x')";

PHP/MySQL - How to select id from table and echo in array

How to make the array of id that we call from a table?
What I want is like this :
$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.
Thank you
Code :
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){
$a = implode(',',(array)$row['id_add_user']);
echo $a;
}
What I get from echo $a is 12345 not 1,2,3,4,5
Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.
$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id_add_user']);
}
echo implode(", ", $result);
Collect necessary values into an array.
$a = [];
while(...){
$a[] = $row['id_add_user'];
}
echo implode(',', $a);
You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL
You can further simplify it to...
$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));
mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.
$array = array(1,2,3,4,5);
Use below SQL query for selecting the array id data
SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;

Separate ids by commas and quotes

I got an array of ids that I want to use inside an IN statement (sql). However this can only be done when it is written correctly, for example: IN ('12', '13', '14')
How can I change an array of ids into that format? This means adding quotes around every number, and after every number surrounded by quotes a comma, except for the last one in the array.
My code:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
I later want to use it like this:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";
Do this as a single query! SQL engines have all sorts of optimizations for working with tables, and doing the looping in your code is usually way more expensive.
The obvious query for your purposes would be:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;
Use implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
Have you tried to implode()?
Use ", " as glue. You will have to edit the string yourself to add a " at the beginning and end.
More info: http://php.net/manual/en/function.implode.php
Alternatively you can use single join query, like this.
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1
If the column's type in the DB is integer you do not actually need to quote the values, but in case it isn't, you can use array_map to quote every item in the array, then implode to join them with commas:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
Result:
SELECT * from mytable where id in ('1','2','3','4','5')
You can do something like this:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
This will give you :
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1

Pass an array as parameters to SQL procedure

I have SQL procedure in which I'm using an IN statment. It goes like this:
SELECT * FROM costumers WHERE id IN('1','2','12','14')
What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?
You can implode on this case:
$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')
or if you do not want any quotes:
$ids = implode(",", $array);
You can use PHP function Implode
$array = array("1","2","12","14");
$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"
implode() is the right function, but you also must pay attention to the type of the data.
If the field is numeric, it is simple:
$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));
But if it's a string, you must play with single and double quotes:
$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));
This should do the trick
$array = array('1','2','12','14');
SELECT * FROM `costumers` WHERE `id` IN('{$array}');
Try imploding the php into an array, and then interpolating that string into the SQL statement:
$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);
SELECT * FROM customers WHERE id in ($string);
use PHP's join function to join the values of an array.
$arr = array(1,2,12,14);
$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";

CodeIgniter - query binding "IN" parameter

I have a following query in my CodeIgniter, which I'm trying to bind via parameter.
$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids = "1,2,3,4";
$this->db->query($q, array($ids));
Above is not working, because the query binding treats $ids as string. How can I parameterize my query, but still be able to do "IN" operation?
EDIT
sorry, I have to use "raw SQL query". Above query is just a part of a much larger + complex query, which I can't use ActiveRecord for. Also I'm using Postgres.
Instead of string put it in array
$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids = array(1,2,3,4);
$this->db->query($q, $ids);
You can achieve same thing like this without binding
Alternative
$ids = array(1,2,3,4);
$this->db->where_in('id',$ids);
$this->db->get('my_table');
Try this with where_in
$ids = array(1,2,3,4);
$this->db->select('*');
$this->db->from('my_Table');
$this->db->where_in('id',$ids);
$this->db->query($q, explode(',', $ids));
or
$this->db->where_in('id', explode(',', $ids))->get('my_table');
Active Records documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select
Use FIND_IN_SET like this
select * from table where FIND_IN_SET('$ids', id);
Try this code:
$ids = "('1','2','3','4')";
$q = "SELECT * FROM my_table WHERE id IN ".$ids;
$this->db->query($q);
you should use the
$ids = array('1','2','3','4');
$this->db->where_in('id', $ids);
The where_in is used in codignitor.
point is
$ids = "1,2,3,4";
$a = array($ids);
//$a[0] = "1,2,3,4";
//not $a[0]=1;$a[1]=2;$a[2]=3;$a[3]=4;
want to keep your style
$ids = "1,2,3,4";
$a = explode(",",$ids);
$q = "SELECT * FROM my_table WHERE id IN ?"
$ids = "1,2,3,4";
$this->db->query($q, explode(",", $ids));

Categories