Having difficulty to concatenate condition and $_POST variables inside a variable - php

I would like to add this line of code
<?php echo(isset($_POST['AgentID'])&&($_POST['AgentID']=='')?' selected="selected"':'');?>
inside
$agentData.='<option value="'.$row['AgentID'].'">'.$row['AgentID'].' - '.$row['AgentName'].'</option>';
I'm having difficulty because of " " and ' ' due to $_POST variables has ' ' also
The whole code is:
<select name="AgentID" id="agentIDSentakushi">
<option value="" <?php echo(isset($_POST['AgentID'])&&($_POST['AgentID']=='')?' selected="selected"':'');?>>--</option>
<?php
$setsu = dbSetsuzoku();
$sql = 'SELECT AgentID,AgentName FROM agentdb ORDER BY AgentID';
$agentData='';
$result = $setsu->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$agentData.='<option value="'.$row['AgentID'].'">'.$row['AgentID'].' - '.$row['AgentName'].'</option>';
}
echo $agentData;
$setsu = null;
?>
</select>

To simplify it, do:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$selected = (isset($_POST['AgentID']) && $_POST['AgentID']==$row['AgentID'])?'selected="selected"':'';
$agentData.='<option value="'.$row['AgentID'].'"'.$selected.'>'.$row['AgentID'].' - '.$row['AgentName'].'</option>';
}
$selected here is a variable which checks if $_POST['AgentID'] is set and if it's equal to $_POST['AgentID'], if the conditions are true, that option will be selected.

I'd go about is using vsprintf like this:
$setsu = dbSetsuzoku();
$sql = "
SELECT
AgentID,
AgentID AS AgentID_2, -- notice how I duplicated it here
AgentName
FROM agentdb
ORDER BY AgentID
";
$agentData = '';
$result = $setsu->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$selected = (isset($_POST['AgentID']) && $_POST['AgentID'] == $row['AgentID']) ? ' selected' : '';
$agentData .= vsprintf("<option value='%d'$selected>%d - %s</option>", $row);
}
echo $agentData;
$setsu = null;
The trick here is to select the parameters you will then later print in the same order (and quantity) in the SQL query since you will pass the returned array directly to vsprintf and the array returned from the SQL query needs to be in the same order as your vsprintf placeholders. Saves you a lot of confusing text :)

Related

Generating a sql query in php using for loop

CODE :
$nerd_result = mysql_query("select * from nerd_profile where nerd_reg_no = '$reg_no'");
$nerd_data = mysql_fetch_array($nerd_result);
$tags = array();
$tags = explode(",",$nerd_data['nerd_interests']);
for($i = 0; $i < sizeof($tags)-1; $i++)
{
if($i != sizeof($tags)-2)
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% or ";
}
else
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% ";
}
}
$proper_query = "select * from `qas_posts` where ".$sub_query." and `post_date` like '%$today%'";
$result = mysql_query($proper_query);
while($each_qas = mysql_fetch_array($result))
Description :
I am adding the like clause along with php variable in a string and concatenating it with the further variables with like clause to come. In the end when I echo I get the perfect query that I want but
mysql_fetch_array()
does not accept that generated query rather if I hard code it , it works perfect what am I doing wrong ?? can I do that ??
When doing string comparisons in mysql you need to make sure you have quotes around your comparison value.
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' or ";
and
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' ";

Using two or more SQL query statements in a PHP loop

$query_country = "select abbr,full_name from Country";
$result_country = $db->query($query_country);//this is the first SQL
foreach ( $result_country as $row ){
echo '<optgroup label="' . $row['full_name'] . '">';
$abbr = $row['abbr'];
$query_airport = "select location from Airport where country_abbr = $abbr ";
$result_airport = $db_other->query($query_airport);//this is the second SQL
foreach ( $result_airport as $row_prime ){
echo '<option>'.$row_prime['location'].'</option>';
}
echo '</optgroup>';
}
As shown above, the 2nd SQL doesn't work.
I tried to NEW a PDO variable( $db_other ) in the 'config.php' file, but it still doesn't work.
My question is that how I can use the second SQL in a PHP loop.
The reason why I want to do this is that I need to make a selection table group by the 'Country name'.
try to quote your query variable and also use db object $db to run query
$query_airport = "select location from Airport where country_abbr = '$abbr' ";
$result_airport = $db->query($query_airport);
Also check $abbr have value so code looks like:-
if(!empty($abbr)) {
$query_airport = "select location from Airport where country_abbr = '$abbr' ";
$result_airport = $db->query($query_airport);
foreach ( $result_airport as $row_prime ){
echo '<option>'.$row_prime['location'].'</option>';
}
}

SQL field being printed as a string

I have a search form to get some records. One of the restricting field for the form is record, being a dropdown box that looks like this:
<select name="record" id="record">
<option value="1">Highest Score</option>
<option value="2">Most runs</option>
</select>
Then when they search the following code runs:
if (isset($_GET['action']) and $_GET['action'] == 'search')
{
include $_SERVER['DOCUMENT_ROOT'] . '/stats/includes/db.inc.php';
$placeholders = array();
if($_GET['record'] == '1'){
$placeholders[':record'] = 'runs';
} else if($_GET['record'] == '2'){
$placeholders[':record'] = 'SUM(runs)';
}
$select = 'SELECT playerid, :record as record, user.usertitle';
$from = ' FROM cricket_performance p INNER JOIN user ON p.playerid = user.userid';
$where = ' WHERE TRUE';
if ($_GET['team'] != '')
{
$where .= " AND team = :team";
$placeholders[':team'] = $_GET['team'];
}
if ($_GET['record'] != '')
{
$where .= " ORDER BY :record DESC";
}
$where .= " LIMIT 10";
try
{
$sql = $select . $from . $where;
$s = $pdo->prepare($sql);
$s->execute($placeholders);
}
catch (PDOException $e)
{
$error = 'Error fetching record';
include 'form.html.php';
exit();
}
foreach ($s as $row)
{
$records[] = array('playerid' => $row['playerid'], 'record' => $row['record'], 'usertitle' => $row['usertitle'], '1' => $row['1']);
}
include 'form.html.php';
exit();
}
And that works perfectly fine, except for one thing. This: $placeholders[':record'] = 'runs'; is quite literally being printed in the SQL as 'runs', instead of the runs field being picked from the database, so $record['record'] will be printed as 'runs' for every entry, instead of the number being picked out of the table.
if the quotations are replaced by "" the same thing occurs, and if replaced by `` nothing happens (empty result)
You shouldn't use placeholders for table or field names. Use a variable instead, the value doesn't need to be sanitized anyway.
"SELECT playerid, ".$field." as record, user.usertitle"
PDO expects bound parameters to be values in e.g. WHERE clauses. Therefore
$s = $pdo->prepare($sql);
$s->execute($placeholders);
won't work as expected. PDO creates from
SELECT playerid, :record as record, user.usertitle
something like
SELECT playerid, 'runs' as record, user.usertitle
and tries to execute.

php mysql multiple field search empty fields

<?php
if(isset($_POST['submit'])) {
$fields = array('field1', 'field2', 'field3');
$conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`".$field."` like '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysql_query($query);
$say = mysql_num_rows($result);
if ($say == 0) {
echo "<tr>no result.</tr>";
} else {
echo '...';
while($row = mysql_fetch_array($result))
{
...
}}
} ?>
Why doesn't this code checking empty fields? It returns results that has empty field even form submits empty.
The only improvement I think of is trim():
if(isset($_POST[$field]) && trim($_POST[$field]) != '') {
however, I am sure it is not the issue.
Have you ever thought of printing the resulting query out?
Look, you're writing a program to create some string (SQL query). But for some reason never interested in this program's direct result, judging it by some indirect results. May be it's data/query logic makes such results, but the query itself is okay?
if the query is still wrong - continue debugging.
Echo everything involved - print variables, condition results, intermediate results in the loop - and look for inconsistencies
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
When form is submitted empty ($conditions=0) it returns all table (select * from customer).
Added an else condition and fixed. Thanks for print query advices.
For checking something is empty or not. You can use empty() method.
Check this:
empty()
isset() only check whether that object/variable is set or not. For more details check this
isset()

implode() [function.implode]: Invalid arguments passed WHEN $_POST['duration'] == EMPTY

I have a multiselect field
<select name="duration[]" id="duration" title="Duration" multiple="multiple" size="3">
<option value="1">1 Months</option>
<option value="2">2 Months</option>
<option value="3">3 Months</option>
</select>
my php code implode multiple values i.e 123 as 1,2,3 and insert it in database. The problem is that the field is not a required field and when i leave it empty it give me error (Invalid arguments passed)
My php code below
$duration = array();
$duration = $_POST['duration'];
if($duration)
{
foreach($duration as $value)
{
$months[] = $value;
}
}
$sql = "SELECT * FROM tbl_courses WHERE duration IN (".implode($months, ',').") ";
thanks in advance
The two problems you have is you try to implode on user input which may not be an array, and your code is vulnerable to SQL Injection.
To address those you should first check if it's an array with is_array(), then check if it has any elements with count(), then finally implode but use array_map() to filter the values to prevent SQL Injection. This will not only prevent SQL Injection but will prevent syntax errors in your query because strings must be quoted in an IN clause.
function getInt($i) {
return (int)$i;
}
$inClause = '';
if(isset($_POST['duration']) && is_array($_POST['duration']) && count($_POST['duration']) > 0)
{
$inClause = 'WHERE ';
$inClause .= implode(', ', array_map('getInt', $_POST['duration']));
}
$sql = "SELECT * FROM tbl_courses $inClause";
$duration = array();
$duration = $_POST['duration'];
$sql = FALSE;
if($duration&&is_array($duration))
{
foreach($duration as $value)
{
$months[] = $value;
}
$sql = "SELECT * FROM tbl_courses WHERE duration IN (".implode($months, ',').") ";
}
if($sql){
//do something with sql
}
use is_array to check if $duration is an array.
Just remove the WHERE condition if it is not required
$sql = "SELECT * FROM tbl_courses";
if (count($months)>0)
$sql .= " WHERE duration IN (".implode($months, ',').") ";
and better use isset($_POST["x"]) instead of just an if.
So let's say $_POST['duration'] is null.
$duration = array();
$duration = $_POST['duration'];
Then you don't have a value to implode on because your foreach is not going to be executed.
One solution would be to put your code into an if( $_POST['duration'] ) respectively if( count($months) )
One of options is typecasting.
$duration = (array)$_POST['duration'];
Since you use contents of $_POST['duration'] in your query be aware of SQL injection techniques.
Check that $_POST['duration'] is set and build your WHERE statement if it is, if not leave it blank:
$where = !$_POST['duration'] ? '' : 'WHERE duration IN ('.implode($_POST['duration'],',').')';
$sql = 'SELECT * FROM tbl_courses '.$where;
I have also removed some of your unnecessary variable declaration and looping around $duration.
Please note you need to sanitise your data to protect against SQL injection. The easiest way in this case would to be to loop through the values and cast them as int:
foreach($_POST['duration'] as $value) {
$months[] = (int)$value;
}
$where = !$months ? '' : 'WHERE duration IN ('.implode($months,',').')';
$sql = 'SELECT * FROM tbl_courses '.$where;

Categories