Multi input & multi column for each loop PHP - php

Currently taking all get request through foreach function. Looking if column called season contains them. Next step is adding 1 more column to check if any get request is LIKE any of the next column values. The second column has to be an AND and not and OR, which means if the first column season contains any of the get requests AND the second column contains any of the GET requests.
Currently:
$array_name = array();
foreach ($_GET as $key => $value) {
$array_name[] = "'%" . escape_string($value) . "%'";
};
$string = implode(' OR season LIKE ', $array_name);
$tank = "SELECT * FROM shrubs2 WHERE season LIKE {$string}";
echo $tank;
First edit:
function searchByColumn($values, $columnName) {
$string = implode(" OR $columnName LIKE ", $values);
return "SELECT * FROM shrubs2 WHERE $columnName LIKE $string";
}
$array_name = array();
foreach ($_GET as $key => $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
$colNames = array("season", "日照"); // can add here more column names
foreach($colNames as $colName) {
$str = searchByColumn($array_name, $colName);
}
echo $str;
///// creating the query with the variable $str

You can define function to search for each column:
function searchByColumn($values, $columnName) {
$string = implode(" OR $columnName LIKE ", $values);
return "SELECT * FROM shrubs2 WHERE $columnName LIKE $string";
}
Then use it as:
$array_name = array();
foreach ($_GET as $key => $value) {
$array_name[] = "'%".escape_string($value)."%'";
}
$colNames = array("season"); // can add here more column names
foreach($colNames as $colName) {
$str = searchByColumn($array_name, $colName);
echo $str; // or run it
}

Related

Get unique value from an array php

I want to display only unique strings and I have this code:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
$array = array_unique($array);
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
echo '' . $value . '<br>';
}
}
I have put an array_unique like this:
$array = array_unique($array);
But it returns this:
word-word
word
word2
word3
word-word
It doesn't print only unique values. What is wrong?
Think the problem is because the strings are being processed after the array_unique operation rather than before it. Try the following instead:
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
}
$array = array_unique($array);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
}
I have resolved, i will post code may be will be good for someone!
$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
$array = array_filter(explode(',', $rez['tags']));
foreach ($array as $key => $value) {
$value = ltrim($value);
$value = str_replace(" ", "-", $value);
$alltags[]=$value;
}
}
$array=array_unique($alltags);
foreach ($array as $value) {
echo '' . $value . '<br>';
}
Explode your string.
Trim outer spaces from each element.
Replace inner spaces with hyphen in each element.
Only keep non-empty elements.
Only keep unique elements (using double array_flip).
Display results.
Code: (Demo)
while($rez=$result->fetch_assoc()) {
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){$clean[]=$v;} // retain non-empty values
}
$clean=array_flip(array_flip($clean)); // double flip is faster than array_unique
foreach($clean as $v){
echo "$v<br>";
}
}
Alternatively, you could do all of the value and html prep in the first foreach loop and then use implode to display the batch. This will remove the potentially unnecessary trailing from final element:
Code:
$rez['tags']=' , word , word-word, word2 , word word, word3,';
$array=explode(',',$rez['tags']); // split into elements
foreach($array as $v){
$v=str_replace(" ","-",trim($v)); // remove outer spaces, replace inner spaces
if($v){
$clean[]="$v"; // prep non-empty values for display
}
}
echo implode("<br>",array_unique($clean));
Output:
word<br>
word-word<br>
word2<br>
word3

How to generate a WHERE clause from an array with multiple AND-conditions

I have an HTML-table, where various selections can be made. The selected variables that contain the respective values, build the array $data[]. Now, with this array I would like to make an SQL request where all selected criteria should be met. This means, that I need the following request:
SELECT * FROM fruitgroups
WHERE $selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
etc ...
Can anybody please help me with the loop that generates exactly the string:
...
$selection[1] = $value[1]
AND $selection[2] = $value[2]
AND $selection[3] = $value[3]
... etc ...
...that I need for the request?
Thank you in advance!
You can make a SQL request like this:
$selection = array("one", "two", "three");
$value = array("Tone", "Ttwo", "Tthree");
$concat = array();
foreach($selection as $key => $var){
$new = $selection[$key] . " = " . $value[$key];
array_push($concat, $new);
}
$concat = implode(" AND ", $concat);
$request = 'SELECT * FROM fruitgroups WHERE ' . $concat . ';';
echo $request;
Run example
Similar to the answer above, but keep it simple and don't forget the single quotes around the values:
$clauses = [];
foreach ($values as $i => $value) {
$conditions[] = "{$selection[$i]} = '$value'";
}
$query = "SELECT * FROM fruitgroups WHERE " . implode(' AND ', $conditions);
Even better, use an ORM like Eloquent:
$conditions = [];
foreach ($values as $i => $value) {
$conditions[$i] = $value;
}
$result = App\FruitGroups::where($conditions)->get();
I'm assuming you are sanitizing your inputs first, of course.

MySql "WHERE" builder

I was thinking of implementing a function to "build" the WHERE clause in an SQL request like so:
"SELECT * FROM table $where"
Building $where with a cycle that would look like this:
$arr=array("Id"=>"1","Time"=>"12:00");
function whereBuild($arr){
foreach ($arr as $key => $val){
$result.=$key.'="'.$val.'" AND ';
}
$result = substr($result, 0, -5); // removes last AND and spaces
return $result
}
$where = whereBuild($arr);
What do you think? Does it make any sense? Could it be achieved in a simpler/better way?
Thank's!
If you are always using AND in your query you can build an array and implode it on return.
$arr = array("Id"=>"1","Time"=>"12:00");
function whereBuild($arr){
$result = array();
foreach ($arr as $key => $val){
$result[] = $key.'="'.$val.'"';
}
return implode(" AND ", $result);
}
$where = whereBuild($arr);

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}

Inserting multiple $_Post arrays into a database

how can I add $_POST['wmeet'] into the auto INSERT or should I do a separate UPDATE. I want all 6 $_POST['wmeet'] values to go into m_wmeet in format "ce1 sf1 sm1" a single space in between each value
if (is_array($_POST['add']))
foreach ($_POST['add'] as $key => $value)
$_POST['add'][$key] = mysql_real_escape_string(stripslashes($value));
if (is_array($_POST['wmeet']))
foreach ($_POST['wmeet'] as $key => $value)
$_POST['wmeet'][$key] = mysql_real_escape_string(stripslashes($value));
function dbSet($fields, $source = array()) {
$set='';
if (!source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`$field`='".mysql_real_escape_string($source[$field])."', ";
}
}
return substr($set, 0, -2);
}
$fields = explode(" ", "m_user m_pass m_email m_date m_ip m_type m_country m_place");
$query_mem = "INSERT INTO social_members SET ".dbSet($fields, $_POST['add']);
mysql_query($query_mem);
One way to try to take advantage of similar syntax between INSERT and UPDATE is to use the implode method mentioned by #KristerAndersson combined with REPLACE INTO. You'll have to have a primary key that is part of your insert or else a unique key for this to work. Since REPLACE INTO shares the same column syntax as INSERT INTO you can just use it and get your UPDATES along with your INSERTS. Keep in mind that REPLACE INTO deletes the old row and inserts a new one so the record key will change.
Try something like this:
if (is_array($_POST['add']))
foreach ($_POST['add'] as $key => $value)
$_POST['add'][$key] = mysql_real_escape_string(stripslashes($value));
if (is_array($_POST['wmeet']))
$_POST['add']['m_wmeet'] = mysql_real_escape_string(stripslashes(implode(' ',$_POST['wmeet'])));
function dbSet($fields, $source = array()) {
$set='';
if (!source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`$field`='".mysql_real_escape_string($source[$field])."', ";
}
}
return substr($set, 0, -2);
}
$fields = explode(" ", "m_user m_pass m_email m_date m_ip m_type m_country m_place m_wmeet");
$query_mem = "INSERT INTO social_members SET ".dbSet($fields, $_POST['add']);
mysql_query($query_mem);
this is what i've put together from the comments/answers ... which one would work?
if (is_array($_POST['wmeet']))
foreach ($_POST['wmeet'] as $key => $value)
$_POST['wmeet'][$key] = mysql_real_escape_string(stripslashes($value));
$wmeet = implode(" ",$_POST['wmeet']);
or does it need to be something like
$_POST['wmeet'][$key] =
mysql_real_escape_string(stripslashes($value = implode(" ",$_POST['wmeet'])));
and then the insert code... would something like this work?
$query_mem = "INSERT INTO social_members
SET ".dbSet($fields, $_POST['add']. ", m_wmeet=".$wmeet);

Categories