PHP - Looping through a QueryString - php

Trying to loop through a querystring in php but only getting last value. What should I be doing to get all values?
example:
querystring = ?style=ranch&style=barn&style=colonial
php:
$sqlStyle = "SELECT DISTINCT COUNT(*) as count FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
$sqlStyle .= $key . " like '%" . $value ."%'";
$i++;
}
echo $sqlStyle;
Result:
SELECT DISTINCT COUNT(*) as count FROM houses_single Where Houses like '%colonial%'

The query parameter "style" is an array in this case and must be identified by square brackets - if not, the last key=value pair will overwrite the others.
?style[]=ranch&style[]=barn&style[]=colonial
$_GET['style'] is an array then you can loop over by using foreach:
foreach ($_GET['style'] as $value) {
// ...
}
if 'style' is not the only parameter you want to add, you can use a is_array() check in the foreach loop:
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
if(is_array($value)) {
$sec = array();
foreach($value as $second_level) {
$sec[] = $key . " LIKE '%" . $second_level."%'";
}
$sqlStyle .= implode(' AND ', $sec);
}
else {
$sqlStyle .= $key . " LIKE '%" . $value ."%'";
}
$i++;
}
echo $sqlStyle;
alternative without foreach:
<?php
$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
if(is_array($_GET)) {
$statement .= ' WHERE';
// create copy to keep the $_GET array
$add_where = $_GET;
array_walk(function($elem,$key){
is_array($elem) {
return implode(' AND ', array_map(function($sec) using ($key) {
return "$key LIKE '%$sec%'";
}, $elem);
}
else {
return "$key LIKE '%$elem%'";
}
},$add_where);
$statement .= implode(' AND ', $add_where);
}
(codes are untested)
Sidenode about safety: I hope you won't use this code snippet you provided in productive environment without any escaping of the parameters.

Related

how to remove string from the end of foreach loop

can I remove the OR from the end of foreach loop
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
$where .= ' OR ';
}
} else {
$s = '';
}
with your condition, i think you use IN for easy.
if (isset($_POST['size'])) {
$size = $_POST['size'];
if($size){
$where .= ' AND `pSize` IN ('.implode(",", $size).')';
}
}
this will also work in your case:
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
for($i=0;$i<count($s);$i++) {
$where .= 'pSize=' . $s[$i];
if($i != count($s)-1){
$where .= ' OR ';
}
}
} else {
$s = '';
}
One way to avoid that issue is create an array and implode.
if (isset($_POST['size'])) {
$where .= ' AND (';
$s = $_POST['size'];
$end = count($s);
//echo $end;
$aWhere = [];
foreach ($s as $ss) {
$aWhere[] = 'pSize=' . $ss;
}
$where .= implode(' OR ', $aWhere) . ')';
} else {
$s = '';
}
Maybe you need parentheses on the Where, I did it for you.
Take care with SQL injection, use prepared statements.
you can go for many ways
way 1:
you can go for for loop instead of foreach()
$a=sizeof($s);
$x=$a-1;
for($i=0;$i<$a;$i++){
if($i==$x){ $where .= 'pSize=' . $ss;
}
else{ $where .= 'pSize=' . $ss;
$where .= ' OR ';
}
}
way2 : use rtrim()
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
$where .= ' OR ';
}
$where=rtrim($where,' OR ');
There are many ways to do this. You can even use a for loop. If you'd prefer a foreach loop, you can create an iterator variable to mimic a for loop as follows:
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
$i = 0;
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
if (++$i != $end)
$where .= ' OR ';
}
} else {
$s = '';
}

Number not getting added in mysql database format ( number - number )

I need to add data in my database and one way or the other the format must be like,
0 - 0 or 1 - 5
i have tryed =>
mysqli_real_escape_string();
but did not work.
i have also tryed changing the sign to / , * , +, exp.
PHP
$dataBase->_insertDataBase('tableNaam', $input);
function _insertDataBase($tabel,$input){
$velden='';
$waarden='';
$i=0;
foreach($input AS $key=>$value){
$i=$i+1;
if($i !== count($input)){
$a=', ';
}else{
$a='';
}
$velden.=$key.$a;
$waarden.=$value.$a;
unset($a);
}
$sql = "INSERT INTO `$tabel`($velden) VALUES ($waarden)";
$this->_conn()->query($sql);
}
The problem is your SQL statement is giving the equation 5-1 as a value, so the server is doing the math and inserting 4 just like you told it to. You need tell it that it's a literal string by surrounding the values with apostrophe's (i.e. '5-1').
Replace:
foreach ($input AS $key => $value) {
$i = $i + 1;
if ($i !== count($input)) {
$a = ', ';
} else {
$a = '';
}
$velden .= $key . $a;
$waarden .= $value . $a;
unset($a);
}
With:
$velden = array();
$waarden = array();
foreach ($input AS $key => $value) {
$velden[] = $key;
$waarden[] = $value;
}
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";
Or possibly even:
$velden = array_keys($input);
$waarden = array_values($input);
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";

automatically generate update form with array

$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= '<div class="form-desc">' . $formDesc . '</div>';
} else {
self::show_error(QUERY_EMPTY);
}
$array = array_values($array);
print_r($array);
$out .= '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>';
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateImgField($fieldname, $value);
}
}
}
$arr = array("last_modified"=>"input", "published"=>"input", "content"=>"textarea");
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);
Right now all fields are outputting in every foreach when only inputs should output in the generateInputField section for example. I know this is because I need to check if the fieldtype (input, textarea) key matches with one of the values marked as input or textarea for values of the $fieldname. But I am not sure how.
I am pretty sure I have to filter the array so only values with input go into a separate array like arrayInput in which I can use as the second argument in in_array.
If I understand you and your code correctly...
This code
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
will always return true for all your rows thats why you are getting your current output.
Instead you should be doing this:
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if ($fieldname == 'input') {
$out .= generateInputField($fieldname, $value);
} elseif($fieldname == 'textarea') {
$out .= generateTextarea($fieldname, $value, $cke);
} elseif ($fieldname == 'img') {
$out .= generateImgField($fieldname, $value);
}
else{ $out = $out;}
}
}
With alot of help from stackers...
/**
* Create Form With Array
*
* Creates a form based on an array. If $do == update, we match fieldnames with values
*
* #param string $table name of database table
* #param string $do whether the form is an insert or update
* #param string $formDesc form description to be echoed
* #param array $array associative array of type (keys), and fieldnames (values)
* #param bool $markFields whether or not to add headers for inputs, textareas .etc during insert
* #param bool $formBrackets whether or not to prepend and append form brackets
* #return $out html form
*
*/
public function createArrayForm($table, $do, $formDesc = '', $id, $array, $markFields = false, $formBrackets = true) {
if (!isset($table) && !isset($do)) {
self::show_error('One or more parameters are missing in ' . __FUNCTION__);
} elseif ($table == 'update' && !isset($id)) {
self::show_error('For this form to be built, and ID must be set. Missing parameter `ID` in ' . __FUNCTION__);
}
if (!is_array($array)) {
self::show_error('For this form to be built, an array must be given. Missing parameter `array` in ' . __FUNCTION__);
}
$result = array();
// create two dimensional array to preserve keys that
// otherwise would be lost with array_flip
foreach($array as $k => $v) {
if (array_key_exists($v, $result)) {
$result[$v][] = $k;
} else {
$result[$v] = array($k);
}
}
// make sure we do not have any duplicates
$result = super_unique($result);
// we just need the array_values for matching with in_array
// however we do not want to run array_values on null
// so we check to see if the $result is a valid array first
// if not, we just output a blank array so in_array doesn't complain
$arrayInput = is_array($result['input']) ? array_values($result['input']) : array();
$arrayTextarea = is_array($result['textarea']) ? array_values($result['textarea']) : array();
$arrayImages = is_array($result['images']) ? array_values($result['images']) : array();
$out = $formBrackets == true ? '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>' : NULL;
if($do == 'insert') {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
$out .= $markFields && in_array('input', $array) ? '<h3>Input Fields</h3>' : NULL;
foreach ($arrayInput as $fieldname) {
$out .= generateInputField($fieldname);
}
$out .= $markFields && in_array('textarea', $array) ? '<h3>Content Fields</h3>' : NULL;
foreach ($arrayTextarea as $fieldname) {
$out .= generateTextarea($fieldname, $cke);
}
$out .= $markFields && in_array('image', $array) ? '<h3>Images Fields</h3>' : NULL;
foreach ($arrayImages as $fieldname) {
$out .= generateImgField($fieldname);
}
} elseif ($do == 'update') {
$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
} else {
self::show_error(QUERY_EMPTY);
}
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayInput)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayTextarea)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayImages)) {
$out .= generateImgField($fieldname, $value);
}
}
}
} else {
self::show_error('Missing array or `do` argument in function ' . __FUNCTION__);
}
$out .= form_hidden('user_data', '1');
$out .= form_hidden('id', $do == 'update' ? $id : self::generateID());
$out .= $formBrackets == true ? form_close() : NULL;
return $out;
}
Usage:
$arr = array("last_modified"=>"input", "published"=>"input", "project_content"=>"textarea", "project_content"=>"textarea");
echo $automate->createArrayForm('projects', 'insert', 'Some form desc', '123', $arr, true);
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);

SQL Query display all numbers between x and y using PHP

Using an html FORM let's convert $core in 100 and $mhz in 1000
emag and koyos are table rows
So if $core is set $parameters['emag'] = "$core"; is emag=100else it is null
AND and WHERE are dinamically setted to appear, so the problem is that I collect all data of variables in $parameters[] and foreach() them.
With my code I am get exactly what $core is. This is the code:
if (!empty($core)) {
$parameters['emag'] = "$core";
}
if (!empty($mhz)) {
$parameters['koyos'] = $mhz;
}
$sql = "SELECT * FROM $tbl_name WHERE 1=1 ";
if (!empty($parameters)) {
foreach ($parameters as $k => $v) {
$sql .= " AND " . $k . "='" . $v . "'";
}
}
$sql .= " ORDER BY emag, performanta_cpu_core DESC, performanta_cpu DESC LIMIT $start, $limit";
And it is results just rows with emag=100, but I have need all numbers equals or little than 100 not just 100
Your query conditions, based on the data you've provided, are:
WHERE 1=1 AND emag = '100' AND koyos = '1000'
And so obviously will only show rows where emag = 100. If you want to show all those up to 100 then change = to <= when the table name is emag:
foreach ($parameters as $k => $v) {
if ($k == 'emag')
{
$sql .= " AND " . $k . "<='" . $v . "'";
}
else
{
$sql .= " AND " . $k . "='" . $v . "'";
}
}
Try this:
foreach ($parameters as $k => $v) {
if ($k == 'emag') {
$sql .= " AND " . $k . "<='" . $v . "'";
continue;
}
$sql .= " AND " . $k . "='" . $v . "'";
}

php foreach error handling in function

I have a function which performs a foreach loop on an array from a database.
see foreach ($teamarray AS $key => $value){$teamgo .= $value[1]." ".$value[2]."<br/>";
Problem is, sometimes there may be no data set, which throws an error when the loop hits that field.
How can i catch/suppress this error?
function GetUnsubmitted($coach){
$push .= "<div id=unsubmitted><h2>Check which event/teams you want to process and click submit</h2>";
$push .= "<form action=\"submit.php\" method=POST>";
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]' AND status = '1' ORDER BY status ASC") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$price = GetPrice($type, "nat");
$teamcount = count($teamarray);
$total = $price * $teamcount;
$teamgo = "";
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
if($statuspre == "1"){
$statuscolor = "#FFCC99";
$statusmsg = "unsubmitted <a href=delsub.php?id=$id onClick=\"return confirm('Are you sure you want to delete this submission?');\"><img src=images/del.png border=0 />";
} elseif($statuspre == "2"){
$statuscolor = "#FFCC66";
$statusmsg = "awaiting confirmation";
} elseif($statuspre == "3"){
$statuscolor = "#66CC66";
$statusmsg = "confirmed";
}
}
$push .= "<div id=submission><div id=event style=\"background-color:$statuscolor;\"><h1>$event</h1><span id=status>$statusmsg</span></div><div id=subinfo><span id=dropdown><img src=images/expand.png border=0></span><h2>$cat >> $subcat >> $division >> $type</h2> <div id=team style=\"display:none;\">$teamgo<br />$price - $total<div id=controls></div></div></div></div>";
$pid .= $id;
$rtotal .= "$total,";
}
$stotal = explode(",", $rtotal);
$gtotal = array_sum($stotal);
$push .= "<div style=\"text-align:right;\"><div id=total>Total - <em>$gtotal</em></div><br><input type=image src=images/paynow.png alt=\"Pay Now\"></form> <a href=submit2.php?$pid&$pidarray><img src=images/mailfax.png width=138px height=41px border=0></a></div></div>";
return $push;
}
If possible id like it to say "no team selected" and stop.
You can write so:
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
foreach expects array. So the really correct way is to ensure that you deal with array before try to iterate, like this:
if (is_array($teamarray) && count($teamarray)) {
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
}
You also can check is_iterable since PHP 7.1.
if ($array) {
foreach ($array as $k => $v) {
...
}
} else {
echo 'No team selected';
// exit from loop
}
Your exit from loop will be a "return", or a "break n" (n is the levels to break for) or continue... it depends on your logic.
if ($value !== null && count($value) >= 3) {
$teamgo .= $value[1] . $value[2]
}
<insert puzzled smiley here>
foreach($row AS $key => $value) {
if ($value) {
$row[$key] = stripslashes($value);
}
}
And:
foreach ($teamarray AS $key => $value){
if ($value && sizeof($value) > 2) {
$teamgo .= $value[1] . $value[2]
}
}
Is this it?
Just do a test if $teamarray actually is an array:
if (is_array($teamarray)) {
foreach ($teamarray as $key => $value) {
// …
}
}
Or you could do:
$teamarray = isset($teamarray) ? $teamarray : array();
Just prior to the loop in a nice tidy line, and it would ensure that you have the variable set to an empty array which would cause it to skip the foreach().

Categories