I have the following code trying to catch up to 15 entries upon submission, however it is only catching the first entry in the database and I am receiving the following error message:
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 '1' at line 1.
<?php
for($i = 0; $i < 15; $i++)
{
$tournament = $_POST['tournament'];
$agegroup = $_POST['agegroup'];
$teamname = $_POST['teamname'];
$coach = $_POST['coach'];
$coachaau = $_POST['coachaau'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$astcoach = $_POST['astcoach'];
$astno = $_POST['astno'];
$astphone = $_POST['astphone'];
$astemail = $_POST['astemail'];
$manager = $_POST['manager'];
$managerno = $_POST['managerno'];
$managerphone = $_POST['managerphone'];
$manageremail = $_POST['manageremail'];
$name = $_POST['name'][$i];
$grade = $_POST['grade'][$i];
$bday = $_POST['bday'][$i];
$aauno = $_POST['aauno'][$i];
if(empty($name) || empty($grade) || empty ($bday) || empty ($aauno))
{
echo ' ';
}
elseif(
$result = mysql_query("INSERT INTO roster (tournament, agegroup, teamname, coach, coachaau, phone, email, astcoach, astno, astphone, astemail, manager, managerno, managerphone, manageremail, name, grade, bday, aauno)
VALUES (
'". mysql_real_escape_string($tournament) . "',
'". mysql_real_escape_string($agegroup) . "',
'". mysql_real_escape_string($teamname) . "',
'". mysql_real_escape_string($coach) . "',
'". mysql_real_escape_string($coachaau) . "',
'". mysql_real_escape_string($phone) . "',
'". mysql_real_escape_string($email) . "',
'". mysql_real_escape_string($astcoach) . "',
'". mysql_real_escape_string($astno) . "',
'". mysql_real_escape_string($astphone) . "',
'". mysql_real_escape_string($astemail) . "',
'". mysql_real_escape_string($manager) . "',
'". mysql_real_escape_string($managerno) . "',
'". mysql_real_escape_string($managerphone) . "',
'". mysql_real_escape_string($manageremail) . "',
'". mysql_real_escape_string($name) . "',
'". mysql_real_escape_string($grade) . "',
'". mysql_real_escape_string($bday) . "',
'". mysql_real_escape_string($aauno) . "');"));
#mysql_query($result)or die(mysql_error());
};
?>
The problem is that you have two mysql_query calls here, and while the first one works on the valid query string, the second - #mysql_query($result) works on its result - i.e., string '1'. But you actually don't need that call, as the first query should have already sent the data to DB.
The quick fix would be checking $result itself (instead of #mysql_query($result)or die(mysql_error()); line):
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Said all that, I'd like to remind you that mysql_query (as whole family of mysql_ functions) is deprecated. If you used PDO or MySQLi, you would be able to use a single prepared statement, filled by new data at each iteration.
Also (kudos to #djot for mentioning that) it's not efficient to extract non-array variables from $_POST again and again, instead of doing it just once - before the loop. This way (if you stay with mysql) you won't have to escape them each time as well. Actually, I'd use something like that here:
$fieldsToInsert = array('tournament', 'agegroup', 'teamname', ...);
$valuesToInsert = [];
foreach ($fieldsToInsert as $field) {
if (! isset($_POST[$field])) {
// actually it's not clear what to do here:
// should we signal an error immediately with, or use some fallback value
}
else {
$valuesToInsert[$field] = mysql_real_escape_string($_POST[$field]);
}
}
This way you'll be able to streamline the code that creates a query as well.
Related
When i update data using php mysql, got some issue, my code php code are here
$query = "UPDATE `wp_experience` SET
`exp_from` ='". $exp_from."' ,
`exp_to` = '". $exp_to."' ,
`exp_title` = '". json_encode($exp_title)."',
`exp_desc` = '". json_encode($exp_desc)."' ,
`exp_cat` = '". $exp_cat."'
WHERE `id` =".$oldid;
it will produce data like,
UPDATE wp_experience SET exp_from ='2016-01-22 00:00:00' , exp_to = '2002-11-14 00:00:00' , exp_title = '{"en":" PSA Peugeot Citroën Automobiles, Mulhouse (F-68)","fr":"Technical Directué - FRENCH","de":"Responsable d'unité de maintenance"}', exp_desc = '{"en":"
Test</p>","fr":"
Test</p>","de":"
H</p>"}' , exp_cat = '18' WHERE id =28
i got this issue,
1064 - 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 'unité de maintenance"}', exp_desc = '{"en":"
Test</p>","fr":"
Test</p' at line 1
How to fix this issue??
Some of your embedded strings breaks your query, so either use mysqli_real_escape_string() or prepared SQL statements:
$query = "
UPDATE
wp_experience
SET
exp_from = '" . $exp_from . "' ,
exp_to = '" . $exp_to . "' ,
exp_title = '" . mysqli_real_escape_string($con, json_encode($exp_title)) . "',
exp_desc = '" . mysqli_real_escape_string($con, json_encode($exp_desc)) . "' ,
exp_cat = '" . mysqli_real_escape_string($con, $exp_cat) . "'
WHERE
id = " . $oldid;
I am looking to insert a single selection into a field for multiple users. I have the following code, when the selection is made and submit is entered. I do not get an error, I get the next page with the message posted 5 times, which is how many users are not it the weekpicks table. But nothing is inserted into the DB.
<?
// This code is to use to place info into the MySQL
$sTeam1 = $_POST['sTeam1'];
// (WHERE username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )" .
//$nMemberID = (integer) Query
$sql_events = mysql_query("SELECT username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )") or die(mysql_error());
while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'" . 'INSERT');
echo "<HTML>
<BODY>
<h2>Your pick of " . ($sTeam1) . ", for week " . ($totalnoOfWeek) . ", has been added.</h2>
<P align=left>Return to main page</p>
</BODY>
</HTML>";
}
?>
You are creating the string for insert but you are not running it.
Fixing your code it'd be:
while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
mysql_query("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'");
//echo ...
}
Fixing the string syntax you could do this, which looks nicer. Also using mysql_real_escape_string() instead of addslashes(), since addslashes is not as safe as mysql's native function for php.
$sTeam1 = mysql_real_escape_string($sTeam1);
mysql_query("INSERT INTO weekpicks SET username = '$username', date_create = NOW(), whatweek = '$totalnoOfWeek', team = '$sTeam1');
Another thing I must tell you:
Stop using mysql_*, use mysqli_* instead.
mysql_ was removed from PHP7 and deprecated after PHP 5.5
It's not as safe as mysqli_, so consider improving your code to the new model.
Follow this guide in order to change your code properly.
I am trying to update some columns in a row with MySQL in PHP like so:
$updateuser_sql = "
UPDATE `users`
SET
`HeaderPictureID` = $insertid,
`Bio` = '" . myre($_POST['Bio']) . "',
`ContactEmail` = '". myre($_POST['ContactEmail']) ."',
`PhoneNo` = '". myre($_POST['PhoneNo']) ."',
`TwitterHandle` = '". myre($_POST['TwitterHandle']) ."'
WHERE
`UserID` = '{$_SESSION['userID']}'
";
$mysqli->query($updateuser_sql);
if($mysqli->errno) {
$handlerreturn['status'] = 'USER_UPDATE_FAILURE';
console.log('FAILED');
} else {
$handlerreturn['status'] = 'EXEC_SUCCESS';
console.log('WORKED');
}
Unfortunately this doesn't work and I get the log 'FAILED'. How can I find out, more precisely, what is wrong and work to fix the issue? Am I doing something so obviously wrong?
Thanks!
Put this at the end of your page
$_POST["Bio"] = "hi";
$_POST['ContactEmail'] = "cheese";
$_POST['PhoneNo'] = "lion";
$_POST['TwitterHandle'] = "asdl";
$_SESSION['userID'] = "asdf";
$updateuser_sql = "
UPDATE `users`
SET
`HeaderPictureID` = 1,
`Bio` = '" . $_POST['Bio'] . "',
`ContactEmail` = '". $_POST['ContactEmail'] ."',
`PhoneNo` = '". $_POST['PhoneNo'] ."',
`TwitterHandle` = '". $_POST['TwitterHandle'] ."'
WHERE
`UserID` = '{$_SESSION['userID']}'
";
echo $updateuser_sql;
It'll spit out the UPDATE statement that is sent to the database. I didn't see any syntax errors from the above. I suspect the problem has to do with your custom "myre" function.
I am stuck with this.
Here is the code:
This is how I call the function,
$res = DataManager::agregarPropiedad($_POST);
here is the function that generate the query and send it,
public static function agregarPropiedad($datos){
$sql = "INSERT INTO propiedades (id_propiedad, nombre, tipopropiedad, descripcion, dormitorios, baños, direccion, localidad, provincia, fecha_alta, sup_cubierta, sup_total)
VALUES (null, '" . $datos['nombre'] . "', '" . $datos['tipo'] . "', '" . $datos['descripcion'] . "', '" . $datos['dormitorios'] . "', '" . $datos['baños'] . "', '" . $datos['direccion'] . "', '" . $datos['localidad'] . "', '" . $datos['provincia'] . "', CURRENT_TIMESTAMP, '" . $datos['supcubierta'] . "', '" . $datos['suptotal'] . "')";
//$sql = "insert into prueba values(null,'".$datos['nombre']."')";
echo $sql;
return DataManager::consulta($sql);
}
When I copy the echo$sql and paste in phpMyAdmin works fine, but when I try to send my function is not inserting anything, but I have no errors. mysql_erros() its empty too.
U can see that, there is a commented $sql. I use that just for test with another table which is much simpler and query the function "consulta" which works fine too.
This is maybe the 40 function that insert things in mysql database, but the first with which I have problems, and I don't know why =(
helppppp...
From personal experience, MySQL queries that work when dumped / copied / pasted into PhPMyAdmin that don't work in code are caused by:
autoincrement / unique field issues
unexpected characters in unprocessed form data
duplicate POST values ( like an array )
mismatched field count
encoding / character set issues
It may well be that if you address the second issue the problem might fix itself. In any case at a minimum you should process you POST(ed) data with strip_tags and add_slashes, but for MySQL mysql_real_escape_string() is strongly recommended.
http://php.net/manual/en/function.mysql-real-escape-string.php
http://www.adminsehow.com/2010/03/prevent-mysql-injection-in-php
There is a problem with your quotes inside the VALUES() and its vulnerable.
<?php
public static function agregarPropiedad($datos)
{
$tipo = mysql_real_escape_string($datos['tipo']);
$nomber = mysql_real_escape_string($datos['nombre']);
$dormitorios = mysql_real_escape_string($datos['descripcion']);
$baños = mysql_real_escape_string($datos['baños']);
$direccion = mysql_real_escape_string($datos['direccion']);
$localidad = mysql_real_escape_string($datos['localidad']);
$provincia = mysql_real_escape_string($datos['provincia']);
$supcubierta = mysql_real_escape_string($datos['supcubierta']);
$suptotal = mysql_real_escape_string($datos['suptotal']);
$sql = "INSERT INTO propiedades (id_propiedad, nombre, tipopropiedad, descripcion, dormitorios, baños, direccion, localidad, provincia, fecha_alta, sup_cubierta, sup_total)";
$sql .= "VALUES (null,'$tipo','$nomber ','$dormitorios ','$baños ','$direccion ','$localidad','$provincia ',CURRENT_TIMESTAMP,'$supcubierta','$suptotal')";
if(mysql_query($sql))
{
return TRUE;
}else{ return FALSE; }
}
?>
I have written a PHP class which will update 4 fields of a certain row in a table. The row is decided by a session var 'user' (which is unique). It's not working, but i'm not sure if it is because of the query or the class itself. So i'm first gonna ask you guys if there are any errors in this query (there probaply are) and when the query is correct, i'll see if the class itself has errors as well.
Query:
UPDATE tblRegistratie(lengte, gewicht, bmi geluk) WHERE `gebruikersnaam` = '" . $_SESSION['regain-user'] . "'
VALUES(
'".mysqli_real_escape_string($conn, $this->Lengte_update)."',
'".mysqli_real_escape_string($conn, $this->Gewicht_update)."',
'".mysqli_real_escape_string($conn, $this->BMI_update)."',
''".mysqli_real_escape_string($conn, $this->Geluk_update)."',
);
The quotes look funny here, but I think your problem is a trailing comma , after the last param:
''".mysqli_real_escape_string($conn, $this->Geluk_update)."',
^^^^^
Last line:
''".mysqli_real_escape_string($conn, $this->Geluk_update)."',
^^//fix the double qoute and make it single '
This is what an UPDATE query should look like.
UPDATE tblRegistratie
SET lengte=mysqli_real_escape_string($conn, $this->Lengte_update),
gewicht=mysql...etc
`bmi geluk`=...etc
WHERE `gebruikersnaam` = '" . $_SESSION['regain-user'] . "'
Yours looks nothing like that.
The correct syntax for UPDATE in MySQL would be something like::
$sql = "UPDATE tblRegistratie SET
lengte = '".mysqli_real_escape_string($conn, $this->Lengte_update)."',
gewicht = '".mysql_real_escape_string($conn, $this->Gewicht_update)."',
bmi = '".mysql_real_escape_string($conn, $this->BMI_update)."',
geluk = '".mysqli_real_escape_string($conn, $this->Geluk_update)."'
WHERE gebruikersnaam = '". $_SESSION['regain-user'];
You need to have your where clause after the values you're setting. Also, it sounds like you have some punctuation issues.
Consider the following rewrite for general easier-to-read goodness:
$query = 'UPDATE tblRegistratie
SET `lengte` = "' . mysqli_real_escape_string($conn, $this->Lengte_update) . '",
`gewicht` = "' . mysqli_real_escape_string($conn, $this->Gewicht_update) . '",
`bmi` = "' . mysqli_real_escape_string($conn, $this->BMI_update) . '",
`geluk` = "' . mysqli_real_escape_string($conn, $this->Geluk_update) . '"
WHERE `gebruikersnaam` = "' . $_SESSION['regain-user'] . '"
';
Also, functions like sprintf() can be your friend. :)
$query = sprintf('UPDATE `tblRegistratie`
SET `lengte` = "%s",
`gewicht` = "%s",
`bmi` = "%s",
`geluk` = "%s"
WHERE `gebruikersnaam` = "%s";',
mysqli_real_escape_string($conn, $this->Lengte_update),
mysqli_real_escape_string($conn, $this->Gewicht_update),
mysqli_real_escape_string($conn, $this->BMI_update),
mysqli_real_escape_string($conn, $this->Geluk_update),
$_SESSION['regain-user']
);
PHP
On the last line you have two initial single quotes.
Fix:
''".mysqli_real_escape_string($conn, $this->Geluk_update)."',
becomes
'".mysqli_real_escape_string($conn, $this->Geluk_update)."',
MySQL
Additionally, your UPDATE syntax appears to be completely invalid. Have a read through the documentation.