I want something like the following:
$arrayOfValues = array(1,2,3,4);
$sqlArray = mysql_convertToSqlArray($arrayOfValues);
which then will return what in SQL would be:
(1,2,3,4)
but in php would be the string "(1,2,3,4)"
There's no builtin function specifically for creating SQL arrays, but you could just join the array and wrap it in parentheses:
$arrayOfValues = array(1,2,3,4);
$sqlArray = '(' . join(',', $arrayOfValues) . ')';
See this in action at http://www.ideone.com/KYApN.
Take a look at http://www.php.net/manual/en/function.implode.php.
This function can be used as following: $sqlArray = "(" . implode(",", $arrayOfValues) . ")";
[Edit]
Ps: join is an alias of implode.
Related
this is my code :
<?php
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
$arr = array();
while ( $tam = mysqli_fetch_array($qqq)) {
$date = $tam['tanggal_awal'];
$reformat_date = date("n-j-Y", strtotime($date));
$arr[] = $reformat_date;
}
$array_date = implode(",", $arr);
?>
> output : 8-9-2018,8-10-2018,8-17-2018
> output i want to is : "8-9-2018", "8-10-2018", "8-17-2018"
could someone help me to get the output i want, thank before.
You can make your code a bit shorter:
$sss = "SELECT tanggal_awal FROM libur_nasional GROUP BY tanggal_awal ASC";
$qqq = mysqli_query($konek,$sss);
while ( $tam = mysqli_fetch_array($qqq)) {
$arr[] = date("n-j-Y", strtotime($tam['tanggal_awal']));
}
$array_date = '"' . implode('", ', $arr) . '"';
In php you don't need to declare an array before pushing values to it.
Your $date variable is not needed as it's just a copy of the $tam['tanggal_awal'] value.
$reformat_date is also not needed as you can place it in the array directly.
The imploding is what is placed between the items, by having ", there you just need to add a " at each end of the string.
$arr=['8-9-2018','8-10-2018','8-17-2018'];
$array_date = '"'.implode('", "', $arr) . '"';
echo $array_date;
Output ---> "8-9-2018", "8-10-2018", "8-17-2018"
Try to implode your array like this.
I have a array like that :
$myarray= 'zzz,aaa,bbb' ;
and want use it in mysql IN clause like that :
"... WHERE ids IN ($myarray) " // didnt work
"... WHERE ids IN ('$myarray') " // didnt work
the error im getting is that the first value in that array zzz says that zzz is not a column name . so i understand that i must separate the values with quotes to be like that :
$myarray= ' "zzz","aaa","bbb" ' ;
But i have no clue to do that . any help would be much appreciated.
$myarray = 'zzz,aaa,bbb';
$myarray = implode("','",explode(',',$myarray));
$query = "..... WHERE ids IN ('$myarray')";
You need to explode() your string and then implode() it -
$myarray = 'zzz,aaa,bbb';
$realArray = explode(',', $myarray);
$stringForIn = "'" . implode("','", $realArray) . "'";
echo "WHERE ids IN ($stringForIn)";
Try that :
$myarray= 'zzz,aaa,bbb' ;
echo implode '"' . ('","', explode(',', $myarray)) . '"';
Hi I have this array called $allextensionsforque. See print_r below.
Array ( [0] => Local/101#from-queue/n,0 [data] => Local/101#from-queue/n,0 )
I'm trying a foreach like below but its not showing any data on the echo. Can anyone help?
$allextensionsforqueu = mysqli_query($conqueue,"SELECT data FROM queues_details WHERE id = '1' AND keyword ='member'");
$allextensionsforque = mysqli_fetch_array($allextensionsforqueu);
$foo = "";
foreach ($allextensionsforque as $extensionrow)
{
$extensionrowstriped = substr($extensionrow['data'],6,3);
$foo = "' " . $extensionrowstriped . " ' ,";
}
echo $foo;
You don't have an array in $extensionrow, since it's only an one dimensional array. So you just need to replace $extensionrowstriped = substr($extensionrow['data'],6,3); with $extensionrowstriped = substr($extensionrow,6,3);.
Check for errors using mysqli_error(). Here is a simple approach, but you may want to improve it for production use:
$allextensionsforqueu = mysqli_query($conqueue,"...") or die(mysqli_error($conqueue));
Next, append your data to $foo instead of overwritting it in each loop:
$foo .= "' " . $extensionrowstriped . " ' ,";
Finally, verify that $extensionrow contains the data that you expect. substr() will return false if a match is not found.
I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);
I have a table "groupdentlink" where I want to delete all the rows that weren't checked in a form.
In essence I want to perform a query like:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id IS NOT IN ARRAY 'b'
I think I could set a variable with a foreach loop and then keep adding the array values to it so I end up with:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id != 'D1'
AND dentist_id != 'D5'
AND dentist_id != 'D8'
...and so on.
But is this really the right/best way to do this?
Thanks in advance!
DELETE FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id NOT IN ('D1','D5','D8')
More info here http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in
If you want to execute this query from a Zend Framework driven application please take in consideration the followings :
$where = sprintf('dentist_id NOT IN ("%s")', implode('", "',array_map('mysql_escape_string', $array)));
$this->sqlMapper->delete($where);
If you try . operator for concatenation purposes the query will result in a fatal error because of the quotes. So from my experience using htmlspecialchars or htmlencode along with . operator will only consume your time and patience. The use of sprintf is elegant, helps you keep your code clean.
And I think these observations apply to any application that makes use of php objects.
New user to Stack Exchange, please forgive and instruct if I'm committing a faux pas.
The preceeding answer is incredibly dangerous, because it opens you up to SQL injection attacks.
Always use bind params.
Always use bind params.
Always use bind params.
Hint: if your query does not resemble "DELETE * FROM groupdentlink WHERE group_id = 'a' AND dentist_id IS NOT IN (?, ?, ?);" you are doing it wrong.
An elegant, fully parametrized solution (using PDO):
$dentistIds = ['D1', 'D5', 'D8'];
$query = sprintf(
"DELETE FROM online_order_shipping
WHERE group_id = 'a'
AND dentist_id NOT IN (%s)",
implode(',', array_fill(0, count($dentistIds), '?'))
);
$stmtDelete = $pdo->prepare($query);
$stmtDelete->execute($dentistIds);
The implode function strings ? together with , without adding a comma in the end (source). You could turn that into a function to make it more readable, otherwise the sprintf keeps it nice and tidy without ugly string concatenation.
I found the statement $str = rtrim($str, ",");
didnt remove the trailing comma giving rise to an
error
I came up with this work around:
// string without quotes
$str = array_shift($array);
// string with quotes
$str = "'" . array_shift($array) . "'";
foreach ($array as $item)
{
$str .= ", '" . $item . "'";
}
Here How I do it :
assuming you have an array called $csvstocknumbers = ['0','1'];
$stocknumbers = implode(",",$csvstocknumbers) ; // make the content of the array in one string seprated by ,
$deleteoldvehicles = "DELETE FROM table_name WHERE column_name NOT IN
($stocknumbers ) ;";
mysqli_query($con, $deleteoldvehicles);
You just need to join the ids with a comma:
$myarray = new array('D1', 'D5', 'D8');
$str = "";
foreach ($myarray as $item)
{
$str .= $item . ",";
}
$str = rtrim($str, ",");
$query = "DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id NOT IN ($str)";
This will give you a query like this:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id IS NOT IN (D1, D5, D8);
If you need the quotes around the ids, then change the loop like this:
foreach ($myarray as $item)
{
$str .= "'".$item . "',";
}