PHP Update query - php

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.

Related

PHP+mySQL - won't update text field from PHP, but will update from adminer with same query

I have this php script:
$query = "UPDATE event_rsvp SET event_note = '" . $_POST[note] . "', event_rsvp_type_id = '" . $_POST[rsvpId] . "' WHERE user_id = '" . $_POST[userId] . "' AND event_id = '" . $_POST[eventId] . "'";
$result = $mysqli->$query;
echo $query;
that echo gives me this:
UPDATE event_rsvp SET event_note = 'test',
event_rsvp_type_id = '4'
WHERE user_id = '1' AND event_id = '1'
Problem is that only the event_rsvp_type_id is updated in database, event_note isn't.
However, if I copy this echo-ed query and paste it directly into adminer or phpmyadmin, it works fine and updates the note as expected.
Any help? Thanks!
Try the following code:
$query = $mysqli->prepare("UPDATE event_rsvp SET `event_note`=?, `event_rsvp_type_id`=? WHERE `user_id`=? AND `event_id`=?");
$query->bind_param("siii", $_POST['note'], $_POST['rsvpId'], $_POST['userId'], $_POST['eventId']);
$query->execute();
Your real problem is that you were missing the singlequotes on your variables, and also, $mysqli->$query doesn't make any sense, the $query part isn't a variable, it should just be query. I converted your code to use prepared statements as well, hopefully this will allow you to see how easy they are to use, while giving you way more security.

mysql gives error when trying to update

My query was:
$query = "UPDATE shop.titem SET
item = $nitem, comment = $comment visible = $visible
WHERE titem.item =$item;";
And the error I get is:
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 'visible = 1 WHERE titem.item =lolipop' at line 2
I noticed that new version of MySQL doesn't really care about the hyphens so I chose to omit that. However, it gives me the same errors even though I use them for the variables.
Help please.
You are missing a commaafter $comment and quotes around string value:
try
$query = "UPDATE shop.titem SET
item = '$nitem', comment = '$comment', visible = '$visible'
WHERE titem.item ='$item'";
Remove the semicolon after $item; inside the query and use '' for the string values
Much better way to write the SQL query is :-
$query = "UPDATE shop.titem SET item = '" . $nitem . "', comment = '" . $comment . "', visible = '" . $visible . "' WHERE titem.item = $item";
Also, I guess it should be shop.item instead of shop.titem.

PHP Array only writing 1st record to MySQL database

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.

sql query works in phpmyadmin but not with mysql_query

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; }
}
?>

hacking an INSERT query to become a mysql UPDATE query

I am a MySQL noob and basically hacking an insert query to become an update query instead. So I am sure it's something simple with the grammar. But what's wrong with this?
// Save data
$mySQLQuery = 'update `'. $fl['mysql_table']. '` SET '. $fl['mysql_query']. "' WHERE speres = '" . mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);
the original INSERT query (working) was
// Save data
$mySQLQuery = 'INSERT INTO `'. $fl['mysql_table']. '` SET '. $fl['mysql_query'];
$rs = #mysql_query($mySQLQuery);
The data is generated here:
$fl['mysql_query'] = "menrecin = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_17'])) . "', menrecvej = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_18'])) . "', menrecser = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_19'])) . "', menrecud = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_20'])) . "', menresmor = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_22'])) . "', menresfro = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_23'])) . "', menresmid = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_24'])) . "', menresres = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_25'])) . "', menrumind = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_28'])) . "', menrumren = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_29'])) . "', menrumved = '" . mysql_real_escape_string(YDFLValue($_SESSION['form']['item_30'])) . "', tekip = '" . $_SERVER['REMOTE_ADDR'] . "', tekbro = '" . $_SERVER['HTTP_USER_AGENT'] . "', tektid = NOW()";
I have an entry with speres = 100525 in the database, so please try:
http://www.konferencer.nu/form/index.php?speres=100525
Good practices of troubleshooting dynamic SQL:
Look at the SQL, not the code that builds the SQL. In other words, echo out $mySQLQuery to see the final SQL, and most of the time you can see the error right away.
Don't suppress errors. Error-checking is helpful and necessary in any code.
It looks to me like your query ends up being:
update `tablename` SET ..., tektid = NOW()' WHERE speres = '...;
So you have a spurious quote after the NOW() and a missing quote at the end.
If you had checked for errors, you'd get something like this:
ERROR 1064 (42000): 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 '' WHERE speres = '...' at line 1
The quoting around the start of the WHERE clause looks odd:
UPDATE `...some table...` SET ...some query... 'WHERE speres = ' ... some criterion ...
Note the single quote placement. Maybe you want to remove the single quotes from inside the double quotes?
you query should look like
$mySQLQuery = 'update'. $fl['mysql_table'].'SET'. $fl['mysql_query'].'= <some value>' ' WHERE speres = '.mysql_real_escape_string($_POST['speres']);
$rs = #mysql_query($mySQLQuery);

Categories