Building a dynamic $_POST statement - php

ingHey guys.
I am wonder the correct syntax for using a $_POST statement in a while loop.
I have written this.
$result_i = $_POST['result_i'];
while ($result_i > 0){
//Get Post Values
$driver = $_POST['driver_update_".$result_i."'];
$BookingID = $_POST['ID_".$result_i."'];
$Task_No_update = $_POST['Task_No_update_".$result_i."'];
//SQL
$driver_update = mysql_query("UPDATE booking SET driver = '$driver', TaskNo= '$Task_No_update' WHERE BookingID = '$BookingID' " );
}
The problem I have is:
$_POST['driver_update_".$result_i."'];
Is it possible to write $_POSTS statements in this way.
Cheers.

The problem is you cannot interpolate variables in single-quoted strings.
Try concatenation instead
$_POST['driver_update_' . $result_i]
or use double-quotes and variable enclosures
$_POST["driver_update_{$result_i}"]
See http://www.php.net/manual/en/language.types.string.php
Also, that looks like an infinite loop as $result_i never changes.

You don't need to wrap everything in quotes here
$driver = $_POST["driver_update_" . $result_i];
$BookingID = $_POST["ID_" . $result_i];
$Task_No_update = $_POST["Task_No_update_" . $result_i];

Related

PHP MySQL Update Set query with Multiple columns

I've tried this query with both commas and "AND" statements as pictured below. I get a syntax error
Something went wrong.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'are available 24/7 by phone and email to answer any questions and to assist you ' at line 1
every time I try this query:
$sql = mysql_query("UPDATE general
SET bookabandheading = $_POST[bookabandheading
AND bookaband = $_POST[bookaband]
AND contactus = $_POST[contactus]
AND aboutuslisten = $_POST[aboutuslisten]
AND contactusheading = $_POST[contactusheading]
AND nightclubsheading = $_POST[nightclubsheading]
AND acousticheading = $_POST[acousticheading]
AND schoolsheading = $_POST[schoolsheading]
AND privateheading = $_POST[privateheading]
AND concertsheading = $_POST[concertsheading]
AND festivalsheading = $_POST[festivalsheading]
AND submissions = $_POST[submissions]
AND interns = $_POST[interns]
AND managementbio = $_POST[managementbio]
AND latestnews = $_POST[latestnews]
AND artistofthemonth = $_POST[artistofthemonth]
AND artistofthemonthphoto = $_POST[artistofthemonthphoto]
AND artistofthemonthid = $_POST[artistofthemonthid]
AND listentoourartists = $_POST[listentoourartists]
AND musicianswanted = $_POST[musicianswanted]
AND aboutus = $_POST[aboutus]
AND bshowcases = $_POST[bshowcases]
AND bandavails = $_POST[bandavails]");
The query worked in a different database on another VPS, but I just migrated servers and it no longer works. Any help is greatly appeciated!
While the main problem is that you missed the closing bracket after bookamandheading, still I would like to advise you to refactor this request for example like this:
$keys = array("bookabandheading", "bookaband", "contactus", "aboutuslisten",
"contactusheading", "nightclubsheading", "acousticheading",
"schoolsheading", "privateheading", "concertsheading",
"festivalsheading", "submissions", "interns", "managementbio",
"latestnews", "artistofthemonth", "artistofthemonthphoto",
"artistofthemonthid", "listentoourartists", "musicianswanted",
"aboutus", "bshowcases", "bandavails");
$set = array();
foreach ($keys as $key) {
$set[] = sprintf(" %s = '%s' ", $key, mysql_escape_string($_POST[$key]));
}
$sql = mysql_query("UPDATE general SET " . implode(", ", $set));
It is much easier to maintain and also a bit more secure by escaping the input.
Update: add where statement example
$where = array();
$where[] = sprintf(" some_string = '%s' ", mysql_escape_string($some_string));
$where[] = sprintf(" some_integer = %d ", $some_integer);
$where = " WHERE " . implode(" AND ", $where);
$sql = mysql_query("UPDATE general SET " . implode(", ", $set) . " " . $where);
I see 3 things wrong with this:
Raw POST data in your query - at the very least user mysql_real_escape_string
The parameters look like strings so should have quotes around them
There's no WHERE option, so you'll update every row in that table
You have a few errors:
Syntax error. Change
$_POST[bookabandheading to $_POST[bookabandheading]
This is also incredibly prone to SQL injections. You should be using mysqli, but if you are set on mysql (which is deprecated as of 5.5.0), you should escape each $_POST variable using mysql_real_escape_string().
Each $_POST variable needs to bee parameterized using quotes a well. So, an example:
$_POST['bookabandheading'] (do this for all $_POST variables)
$_POST[bookabandheading
change to
$_POST[bookabandheading]

SQL syntax error edit post

getting :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

Session variable is not working in MySQL statement

I am trying to use session variable($_SESSION['asc_id'], which holds some value like "AS0027001") in an SQL statement, but it is not working.
When I hardcode the value, it is providing results.
Can anyone please correct me.
MySQL query which is not working
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "$asc_id"
and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Mysql query which is working
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "AS0027001" and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Variable substitution only works within double quoted strings, not single quoted ones. In other words, you should do;
$rs = mysql_query("select .... and asc_id = '$asc_id' and ... limit 0,10", $dblink);
Btw, you did make sure the value doesn't include any characters that may lead to SQL injection, right? Otherwise you should use mysql_real_escape_string to make sure before inserting it into a query.
When you print the strings, it will be clear. When the question is reformatted to leave the SQL readable, the problem is clear. (The first rule for debugging SQL statements is "print the string". A second rule, that makes it easier to comply with the first, is always put the SQL statements into a string which you pass to the SQL function.)
You use the . notation to embed the request term in the string; you don't use that to embed the $asc_id into the string. You should also use mysql_real_escape_string() on the session ID value to prevent SQL injection.
First print the variable $asc_id . If it displays nothing, session is unavailable . In that case you missed session_start() in top of the current executing page .
From the SQL query, you cannot replace the value of a variable inside single quoted string .
Use . symbol for mixing string value with variable or use double quoted string . I prefer first one .
For troubleshooting , simplest method is printing variable values. From the result , you will understand what is missing .
Thanks
Try this. from the comment you added, I modified it like this
session_start(); //add this if you did not do it yet
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query("select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = '$asc_id'
and lname_fname_dob like '".
mysql_real_escape_string($_REQUEST['term']) .
"%' order by lname_fname_dob asc limit 0,10", $dblink);

PHP/mySQL: How do a concatenate a variable in a mysql query? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 1 year ago.
What is the proper way to concatenate text and a variable in PHP inside a mysql_query? Here is my attempt:
page.'$pageID'
I want it to output page3.
Here is all of the code (simplified to focus on the mysql_query):
if ($_POST['pageProgress']) {
$pageProgress = $_POST['pageProgress'];
$pageID = 3;
$userID = 1;
$updateUserProgress = mysql_query("UPDATE test SET page.'$pageID'='$pageProgress' WHERE userID='$userID'") or die(mysql_error());
}
All of the code works perfectly if I simply replace page.'$pageID' with page3.
You do not need the .. PHP parses double quoted (") strings and replaces the variables with their values. As such:
$pageID = 3;
echo "UPDATE test SET page$pageID = '$pageProgress' WHERE userID = '$userID'";
http://codepad.viper-7.com/uIdqqH
The problem is that your .'$pageID' is inside the double-quoted string; you don't concatenate this on the MySQL side; it gets parsed long before MySQL ever sees it.
It might be that you were trying to escape the field name for Mysql, in that case, you use backticks.
Try:
'UPDATE test SET `page'.$pageID.'`=\''.$pageProgress.'\' WHERE...'
Or, much easier on the eyes:
"UPDATE test SET `page{$pageID}`='{$pageProgress}' WHERE..."
"UPDATE test SET page".$pageID."='".$pageProgress."' WHERE userID='".$userID."';"
Dots are in the wrong spot to do it with PHP's string functions.
Something like this.
mysql_query("UPDATE test SET page" . $pageID . " = '" . $pageProgress . "' WHERE userID = " . $userID)
Try
mysql_query('UPDATE test SET page'.$pageID.'='.$pageProgress.' WHERE userID='.$userID)
$updateUserProgress = mysql_query("UPDATE test SET page".$pageID." = '".$pageProgress."' WHERE userID='".$userID."'") or die(mysql_error());
#Marc B ; that's not the question..
You don't need to concatenate anything. you do need to sanitize your variable from post though.
if ($_POST['pageProgress']) {
$pageProgress = mysql_real_escape_string($_POST['pageProgress']);
$pageID = 3;
$userID = 1;
$updateUserProgress = mysql_query("UPDATE test SET page$pageID='$pageProgress' WHERE userID='$userID'") or die(mysql_error());
}

MySQL query php variable in variable?

I have a PHP function that makes a query to MySQL DB.
function regEvent($event, $l)
{
$sqlz_upd="UPDATE {$event} SET f1a='$_POST[F1A"'.$l.'"]'";
The question is what is the syntax to use variable $l in $_POST[F1A$l]?
$condition = $_POST["F1A" . $l];
$sqlz_upd="UPDATE {$event} SET f1a='".mysql_real_escape_string($condition)."'";
This is how to use your dynamic post and be safe for Sql Injection.
Here you go:
$var = mysql_real_escape_string($_POST["F1A".$l]);
$sqlz_upd="UPDATE {$event} SET f1a='$var' ";
if you are using a string as key in an associative array. It should be enclosed in single or double quotes(though PHP won't give any error).
i.e. $_POST['F1A'. $l] or $_POST["F1A$l"]
my suggestion will be...
$sqlz_upd="UPDATE {$event} SET f1a='" . $_POST["F1A$l"] . "'";

Categories