This is the code (I'm using Codeigniter):
$sql = 'SELECT * FROM foo WHERE bar IN (?)';
$query = $this->db->query($sql, array($values));
So $values is an array of strings that I want to add in the SQL statement where the "?" is. When I try this I get an "Array to string conversion" error. Is there any way I can add the values of the $values array as comma separated strings into the SQL statement?
Why don't you use simple codeigniter way
$this->db->from('foo');
$this->db->where_in('bar',$values);
$query=$this->db->get();
This will produce what you exactly want
Update
If you are strict with your way you need to produce the $sql this way
$sql = 'SELECT * FROM foo';
if(is_array($values)&&sizeof($values)>0)
{
$sql.=' WHERE bar IN (';
foreach($values as $key=>$value)
{
if($key==0)
{
$sql.='?';
}
else
{
$sql.=',?';
}
}
$sql.=')';
}
$query=$this->db->query($sql,$values);
You should pass string with comma separated in query. for that use implode function of php.
Do like this:
$values = array('bar1', 'bar2', 'bar3');
$string = "'".implode("',", $values)."'";
Then pass string in the query,
$sql = 'SELECT * FROM foo WHERE bar IN ($string)';
$query = $this->db->query($sql);
echo '<pre>'; print_r($query->result_array());
You will data in $query variable.
Let me know for further help if needed.
Related
I am trying to pass a array in sql query.
Array contains coloumn names as index they are assigned to their respective values which i got using GET method.
for example iam trying to compile this code :
$a='email';
$b=array($a => $_GET['x']);
$sql="SELECT * FROM users WHERE $b";
echo $sql;
The output that i need is:
SELECT * FROM users WHERE email='/*value of $_GET['x']*/'
the output that i am getting is:
SELECT * FROM users where Array
can some one help me how to make it work.
You need to manipulate the $b array to make it into the string your after, at the moment it's just dumping the content in it's own format.
This version will do what your after...
$b=array($a => $_GET['x']);
$columns = [];
foreach ( $b as $name => $value ) {
$columns[] = "$name = '$value'";
}
$sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
echo $sql.PHP_EOL;
I've made it use and as the condition linking multiple columns, you can change this depending on your requirement.
This version instead uses bind parameters, the place holder is inserted instead of the value in the query and then you will need to bind the $data array to the prepared statement (how depends in the API your using). This is safer and more flexible (and recommended)...
$b=array($a => $_GET['x']);
$columns = [];
$data = [];
foreach ( $b as $name => $value ) {
$columns[] = "$name = ?";
$data[] = $value;
}
$sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
echo $sql.PHP_EOL;
//Laravel code
This is my php code I am not getting what is the error and where,please any one help me out
static function getall($input) {
$sql = "SELECT * FROM radio_city";
$where = [];
$params = [];
if ($input['city']) {
$where[] = "city = ?";
$params[] = $input['city'];
} else {
$where = '';
}
$sql .= $where;
$sql .= "\nGROUP BY city";
//echo $sql;
return DB::select($sql, $params);
}
$input and $where are both arrays and you're attempting to coerce string concatenation.
The lines in question are
$sql = "SELECT * FROM radio_city WHERE city=".$input."";
and
$sql .= $where;
I'm not sure what you're trying to do, but it appears to me that you should remove everything after "WHERE" in your stub SQL query.
Also, you'll have to make up your mind with respect to $where's datatype, in either case you don't need that else block that sets $where to an empty string. So either initialize $where to an empty string and concatenate each condition with AND/OR, or initialize to an array and push either AND or OR conditions and then implode before concatenating to your stub.
Edit: just a shot in the dark of what you're looking for...
static function getall($input) {
$where = [];
$params = [];
$sql = 'SELECT * FROM radio_city';
if (isset($input['city']) && $input['city']) {
$where[] = ' city = ?'; // Subsequent additions to $where should specify AND/OR conditional
$params[] = $input['city'];
}
$sql .= implode(',', $where);
$sql .= " GROUP BY city";
return DB::select($sql, $params);
}
Untested. Don't just copy & paste though. If it works, great, but see what's changed and try to really understand why it changed, or ask here if you don't know.
This:
$sql = "SELECT * FROM radio_city WHERE city=".$input."";
Contradicts this:
if ($input['city']) { ....
What is $input? Is it an array? Is it a string? If it is an array, as I suspect and as the second line suggests, the error will be with the first, and you probably want:
$sql = "SELECT * FROM radio_city WHERE city=" . $input['city'];
...though the second line suggest you aren't sure if $input['city'] exists. Incidentally, better use empty() there:
if ( ! empty($input['city'])) { ....
As what you're doing is trying to evaluate what it appears you intend to be a string as a boolean value.
As Utkanos comments, though, Whoa! Format the code, consider the logic more fully. Not much point worrying about whether $input['city'] exists after you've concatenated it onto a string...
I have json array as below
$q=[{"con0":0},{"con1":1},{"con2":2}]
I want to pass this array to select query where query is as follows
$query="select * from table_name where con0='0' and con1='1' and con2='2'";
Shall we use json array to create this query?
The two tricks are to turn the json into a php array via json_decode and then use reset() and key() functions to get the column and condition. Here is the live example:
http://ideone.com/wp1kb1 you can read more about key http://php.net/key and reset http://php.net/reset
<?php
$q='[{"con0":0},{"con1":1},{"con2":2}]';
$ar = json_decode($q, true);
$where = array();
foreach ($ar as $condition) {
$value = reset($condition);
$column = key($condition);
$where[] = " `$column` = " . (int) $value;
}
$whereString = implode(' AND', $where);
$query="select * from table_name where $whereString";
echo "\n $query \n";
Use json_decode to make this an object/array and then use a loop to make a string for that and append to the sql query.
Loop the JSON decoded data inside a foreach, then grab the key-value pair , store them in an array and after the end of the loop, do an implode() on the array with AND and now pass the string to your query as shown.
$json='[{"con0":0},{"con1":1},{"con2":2}]';
$qstr=array();
foreach(json_decode($json,true) as $k=>$arr)
{
$qstr[]="`".key($arr)."`"." = ".$arr[key($arr)];
}
$qstr = implode(' AND ',$qstr); //looks like `con0` = 0 AND `con1` = 1 AND `con2` = 2
$query="select * from table_name where ".$qstr;
I am trying to update one row in my database like this.
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
Can anyone please help me?
I want this data to only update one row, and the data must be separated by a comma.
I am thinking maybe a FOR loop, but I'm not quite sure.
just use implode() function .
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
$sizes=implode(",",$sizes);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
The PHP implode function will serve your purpose.
implode joins array elements into a string separated by the glue we specify. The syntax is:
string implode ( string $glue , array $pieces )
Refer to: http://in3.php.net/manual/en/function.implode.php
Example:
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
?>
there is a catch when you create database never name your table as "Available Beds" i mean don't use space try using "AvailabaleSizes" or Available_Sizes or "availableSizes" after this change write your query like below.
($con, "UPDATE `beds` SET Available_Sizes = '$sizes' WHERE ID = '$prod_id'");
I am trying to create functions to run mysql queries
How would I do things like insert queries. I was thinking
function insert_query ($table,$cols,$values)
{
$sql="insert into $table ($cols) values ($values) "; ...etc
}
With the rest of the query code in the function. But how would I add multiple columns and values?
Should I make $cols and $values An array inside the function?
This is a function of my Database Class.
public function insert($table,$values){
$fieldNames = "";
$fieldValues = "";
foreach($values as $key => $value){
$fieldNames .= "$key,";
$fieldValues .= "$value,";
}
$fieldNames = substr($fieldNames,0,-1);
$fieldValues = substr($fieldValues,0,-1);
$sql = "INSERT INTO $table($fieldNames) VALUES ($fieldValues)";
$this->newConnection();
$result = $this->mysqli->query($sql);
$this->closeConnection();
return $result;
}
Here is what I'm using. Pass field name and Value as Array key and value. $lsQry is an array of field name & value pair
function insert_record($table,$lsQry)
{
$fields_str = implode(',',array_keys($lsQry));
$data_str = implode("','",$lsQry);
$data_str = "'" . implode("','", $lsQry) . "'";
$lsQry = "INSERT INTO $table($fields_str) VALUES($data_str)";
$rs = mysql_query($lsQry);
if(isset($rs))
return true;
else
return false;
}
Please Note
For this function, do consider that function is getting an array of fields name and value pair. It is assumed that htmlentities() and addslashes() or any escaping functions are already applied while creating array from post/get values.
Easy, just us arrays
function insert_query ($table,$cols,$values){
$sql="insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
insert_query('exampleTable', array('column_1', 'column_2', 'column_3'), array('a', 123, 'c') );
The implode for the values requires a small sidenote:
Strings always required being wrapped in quotes. Therefor I made the implode with single qoutes. The downside to this is that integets (like 123 in the example) also get wrapped.
This is not a big problem, but if you want you could replace the implode with a foreach that uses is_numeric to check wether it should be wrapped in quotes.
IMPORTANT SECURITY NOTE:
In this example I havent used proper seurity, like escape_string(), this has to be added! I've not added thos to keep the examples smaller
Another approach could be key/value-usage of an array:
function insert_query ($table,$data){
$cols = array_keys($data);
$values = array_values($data);
$sql = "insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
$info = array('column_1'=>'a', 'column_2'=>123, 'column_3'=>'c');
$info['example'] = 'Easy method to add more key/values';
insert_query('tableName', $info);
In this case you can use functions similar to codeigniter functions.
Use arrays to store table name and columns or values
For example:
$data = array('hid' => $hcsdate,'start_date' => $sdate, 'end_date' => $edate, 'title' =>$title);
Here $data holds the column name and corresponding values.
And pass this $data to another functions for insert, update etc..