Syntax for UPDATE of a record in MYSQL - php

Is the following update query a legal statement? It replaces the existing value with an empty value instead of the word gossamer. It does not fail as far as I can tell. It changes the value in the database from whatever it was before to empty.
$sqld = "UPDATE mynotes SET notes = 'GOSSAMER' WHERE id = '2039'";
$resupdate = mysql_query($sqld) or die(mysql_error());
if ($resupdate) {
$success=1;
$message .="success with update";
}
The query is part of an an API and it returns a result in JSON. While this makes debugging more time consuming, this should be besides the point. If the above is an entirely legal update statement, then at least I can rule out a syntax issue and search for the problem elsewhere.
I have verified that the above code does work in a standalone php file. Something else in code is causing the issue.
Yes, mysql is deprecated in favor of mysqli and PDO. But upgrading legacy site is not in job scope.

It replaces the existing value with an empty value instead of the word gossamer
Assuming this statement is accurate then either:
1) the attribute 'notes' is of type ENUM whose values do not include 'Gossamer'. But you didn't share the DDL for the table.
2) Your code is not executing the query you've shown us here - the query it is executing should be in your MySQL logs

Related

PHP PDO query not inserting - Error HY093

After a lot of searching the web, the times I see this error, it looks really scenario specific. So far, I haven't found one that matched my scenario. I think my issue is coming from a prepared statement with spatial data type params.
The way I'm executing my code is:
$sql = $conn->prepare("INSERT INTO states(`name`, `poly`) VALUES(':name',GeomFromText('GEOMETRYCOLLECTION(:coords)'));");
$res = $sql->execute(['name'=>$name, 'coords'=>$coords]);
if($res){
echo "... Successfully Inserted<br><br>";
}
else{
echo "... Failed<br><br>";
print_r($sql->errorInfo());
echo "<br><br>";
}
The above is failing. The connection to the database has been tested. Since these are rather large geometry sets, instead of pasting my code, I'll show how I verified my SQL:
Dumping a raw SQL file and copy/pasting the SQL into a phpMyAdmin window, everything inserted just fine.
$sqlStr = "INSERT INTO states(`name`, `poly`) VALUES('$name',GeomFromText('GEOMETRYCOLLECTION($coords)'));";
$check = file_put_contents('./states/'.$name.'2.sql', $sqlStr);
So it's because of this, that I believe my sql is correct, but it my problem is likely due to the prepare/execute portion somehow. I'm not sure if spatial data types can't be assigned like this?
Edit
I also want to note that I am on PHP version 5.5.9 and I've executed queries in the original method, with the params in the execute just fine.
There's no way the code at the end could be working. Parameters in the query must not be put inside quotes.
Since GEOMETRYCOLLECTION(:coords) has to be in a string, you need to use CONCAT() to create this string.
$sql = $conn->prepare("
INSERT INTO states(`name`, `poly`)
VALUES(:name,GeomFromText(CONCAT('GEOMETRYCOLLECTION(', :coords, ')')));");

SQL query syntax (variable stays empty)

I'm trying to output a simple list with all the usernames registered on a single e-mail address in our database. The SQL queries necessary for it shouldn't be too hard, but apparently they are too hard for me - here's my issue:
$sql = "SELECT emailaddress FROM ".db_prefix("accounts")." where acctid = '$mailid'";
$mailadress = db_query($sql);
That one's working just fine - I'm declaring mailid in a earlier part of the code, and with that query I can output the e-mail adress (for debugging) of the currently logged in user without any problems. Fine so far.
$sql = "SELECT name FROM ".db_prefix("accounts")." where emailadress ='$mailadress'";
$charakterliste = db_query($sql);
Here's the issue: $charakterliste seems to stay empty, even though I'm pretty sure my syntax is correct. var_dump() and print_r() don't return anything that would point towards the array/variable containing something.
I've double checked and executed a similar query directly in the SQL database and found no problems there - all the fields I'm calling do exist, and the DB connection is fine too. I guess something is wrong in my syntax for the second SQL query? I'd want to list all the names saved in the $charakterliste afterwards with a foreach loop, but as of now there doesn't seem to be anything to list saved in there, although there should be.
Thanks in advance!
Are you sure the column 'emailadress' exist?
Maybe it's 'emailaddress' with two 'd'?
According to your first line of code it should be 'emailaddress'.
$sql = "SELECT name FROM ".db_prefix("accounts")." where emailaddress ='$mailadress'";
$charakterliste = db_query($sql);

Retrieving Data From One Table To Another Table With Different Columns

Trying to retrieve information from the database t_awhole and input it into a_whole. I've read up on a lot of these, but cannot find anything specific to my question.
The code stops where I have placed the comment //>>>>Stops here<<<<<. I used an echo statement to find that it does not pass this point.
This is a email confirmation function, so t_awhole's table structure is different than a_whole. Everything is the same but in t_awhole the first column is a confirmation code associated to to that user. Once they click the link in their email, the row with that confirmation code should transfer all the data from that t_awhole into a_whole. However, it should not transfer the confirmation code, but should add a new column for the number of the row (first column) as an increment, and whether the user is an admin or not (last column). Everything else will stay as it was (fN, lN, aI, eml, pss) in between that first and last row. Please tell me how to do this. Someone attempted below, but his answer was difficult to understand (although he tried and I thank him for that).
Finally, I am using PDO as the structure. It was originally written in mysql. I notice a colon : is used instead of a money sign $. How do I switch this to be from sql to PDO?
<?php
include('db.php');
// passkey that got from link
$pk=$_GET['pk'];
$t_awhole_conf="t_awhole";
// Retrieve data from table where row that match this passkey
$sql_conf1="SELECT * FROM $t_awhole_conf WHERE confirm_code ='$pk'";
$result_conf=mysql_query($sql_conf1) or die ('Error updating database: '.mysql_error());
// If successfully queried
if($result_conf){
// Count how many row has this passkey
$count=mysql_num_rows($result_conf);
// if found this passkey in our database, retrieve data from table "t_awhole"
if($count==1){
$rows=mysql_fetch_array($result_conf);
$fN = $rows['fN']; // capitalizes the first letter (6-26-14)
$lN = $rows['lN']; // capitalizes the first letter (6-26-14)
$aI = $rows['aI'];
$eml = $rows['eml'];
$pss = $rows['pss'];
$pss2 = $rows['pss2'];
$a_whole_conf="a_whole";
// Insert data that retrieves from "t_awhole" into table "a_whole"
$sql_conf2= $conn->prepare("INSERT INTO $a_whole_conf(fN, lN, aI, eml, pss, admin)
VALUES ($fN, $lN, $aI, $eml, $pss, $admin)");
//>>>>Stops here<<<<<
$result_conf2=$sql_conf2->execute() or die ('Error updating database: '.mysql_error());
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}
// if successfully moved data from table"t_awhole" to table "a_whole" displays message "Your account has been activated" and don't forget to delete confirmation code from table "t_awhole"
if($result_conf2){
echo "Your account has been activated";
// Delete information of this user from table "t_awholeb" that has this passkey
$sql_conf3="DELETE FROM $t_awhole_conf WHERE confirm_code = '$pk'";
$result_conf3=mysql_query($sql_conf3);
}
}
?>
TO ANSWER THE QUESTION YOU ASKED
The colon (:) is used in SQL text to identify a placeholder for a named bind parameter within a prepared statement. That colon gets included in the SQL text, and value for that placeholder is provided when the SQL statement is executed.
The "money sign" identifies a PHP variable; in the string context, the variable is evaluated, and the value of the variable gets incorporated into the SQL text.
The following is not an answer to the question you asked. But I think this will answer several other questions you should be asking...
The inclusion of "unsafe" values in PHP variables is where the "SQL Injection" vulnerability comes in, if we don't have any guarantee that the value of the variables don't contain some characters that will be interpreted as SQL. And that's exactly why the mysql interface includes the mysql_real_escape_string function. This is a "wrapper" that inspects values, and properly escapes values so that they will be seen as values, and not be interpreted as SQL syntax.
Q: 1. The code stops where I have placed the comment //>>>>Stops here<<<<<.
A: Cool. It's not clear how you know the code "Stops here", if you're getting some sort of error or what.
We don't see any declaration or assignment for the reference to the $admin variable. We do see that we expected column pss2 to be retrieved by the SELECT. But we don't see anything be done with that, except to assign that to a PHP variable named $pss2, and that doesn't appear to be referenced anywhere else. Curious.
Q: 2. This is a email confirmation function, so t_awhole's table structure is different than a_whole. Everything is the same but in t_awhole the first column is a confirmation code associated to to that user. Once they click the link in their email, the row with that confirmation code should transfer all the data from that t_awhole into a_whole. However, it should not transfer the confirmation code, but should add a new column for the number of the row (first column) as an increment, and whether the user is an admin or not (last column). Everything else will stay as it was (fN, lN, aI, eml, pss) in between that first and last row.
A: Seems like an awkward design. It's not clear why you need to loop through all the individual rows returned by a SELECT (and your code is subject to SQL injection. Hopefully, "Little Bobby Tables" doesn't register... http://xkcd.com/327/)
I'm not sure why you don't just run a single INSERT .. SELECT statement to "copy" the rows from one table to the other in one fell swoop, for example:
$sql = "INSERT INTO a_whole
( fN , lN, aI, eml, pss, admin)
SELECT t.fN, t.lN, t.aI, t.eml, t.pss, '' AS admin
FROM t_awhole t
WHERE t.confirm_code = '" . mysql_real_escape_string($pk) "'";
(I don't see any declaration or assignment to $admin in the original code, so I replaced that reference with a literal string (zero length) in the example above.)
If you were going to do this with PDO, you could use a prepared statement with a bind placeholder. All of the SQL is the same, with the exception that we replace a reference to the value of the PHP $pk variable with a bind placeholder in the SQL text:
$sql = "INSERT INTO a_whole
( fN , lN, aI, eml, pss, admin)
SELECT t.fN, t.lN, t.aI, t.eml, t.pss, '' AS admin
FROM t_awhole t
WHERE t.confirm_code = :pk";
Now the SQL text is a constant string, and is not subject to SQL injection.
With PDO, you'd first call the prepare(), and then call bind_param() and execute(), e.g.
$sth = $dbh->prepare($sql);
$sth->bindParam(':pk', $pk, PDO::PARAM_INT);
$sth->execute();
BUT... to do that, you need to have a PDO connection (referenced as $dbh above); you can't use a mysql connection with PDO.
(If you don't check the result from each call, you'd want to set the error handling on the connection to throw an error, and use a try/catch block to catch any PDOException.)
UPDATE: actually, I see that your code only copies the first row returned from the SELECT, we don't see a normal while (fetch) loop we usually see. That was my oversight there, seeing something I expected but that wasn't there. That's my bad. Still, there's no need to retrieve the values into PHP variables, if all we are going to do with them is insert them into another table. Let the database do that, without mucking up the code with a bunch of variables we don't need.
Q: 3. Finally, I am using PDO as the structure. It was originally written in mysql. I notice a colon : is used instead of a money sign $. Why is this and where would I switch the : for the $ in my code?
A: The code modified in the edit, is now calling functions both from the deprecated mysql interface; and PDO (per the references to PDO functions.)
It's not valid to mix mysql interface functions and PDO interface functions. You can't use PDO functions on a connection obtained using the mysql interface, etc.
This is likely why your code "stops here".
(I was a little confused earlier; I didn't see the PDO functions, all I saw was mysql functions. We're not used to seeing mysql and PDO functions mixed like this, mostly because we never see this because it's not valid.)
TO ANSWER THE QUESTION YOU ASKED
The colon (:) is used in SQL text to identify a placeholder for a named bind parameter within a prepared statement. That colon gets included in the SQL text, and value for that placeholder is provided when the SQL statement is executed.
The "money sign" identifies a PHP variable; in the string context, the variable is evaluated, and the value of the variable gets incorporated into the SQL text. (This is where the "SQL Injection vulnerability comes in... we don't have any guarantee that the value of that variable doesn't contain text that will be interpreted as SQL.
And that's exactly why the mysql interface includes the mysql_real_escape_string function.

Using reserved word in sql update query in php overwrites the whole table

I am currently working on a php project and used the word 'value' as a column name. The problem being that when I run the query, it overwrites all entries in the database, even though I have a delimiter (primary key = *). I have tried everything I can think of to get this to work, and it hasn't yet. here is the complete line of code:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = ".$_POST['txtValueBalance'].", Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
Note here, that $row['FK_Rev_Exp'] is the delimiter I was talking about. It is being pulled accurately from a previous query. Also, please ignore any sql injection problems, I'm just working on getting the project functional, I can optimize later.
EDIT 1: I have also tried enclosing the "value" in everything I can think of that may get rid of this problem, but no luck.
EDIT 2: I also don't think it is a problem with the statement itself, as I directly entered the statement into the mysql command line and it only affected 1 row, possibly a php problem?
EDIT 3: Full block, including the execution of the sql. Here, ExecuteSQL runs all necessary mysqli statements to execute the sql command. it takes in a sql statement and a true/false if there is a result set:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = '".$_POST['txtValueBalance']."', Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
ExecuteSQL($SqlStatement, false);
I can't figure it out, and any help would be appreciated.
I think your problem is not about mysql reserver keywords because your correctly surrounded Value with backtick and that makes database understand this is a field. I'm more concerned about treating not integers as integers so i would suggest to surround with quotes '' your value since it is a decimal
`Value` = '".$_POST['txtValueBalance']."',

mysql_query update doesn't update

mysql_query running an UPDATE query isn't working for me, what am I doing wrong?
if($get_ip['user_ip']== ''){
$insert_ip = mysql_query("UPDATE user SET user_ip='$user_ip' WHERE username='$username' AND password='$password'");
if(!$insert_ip){
$message = 'invalid query'.mysql_error();
die($message);
}else{
echo ('success!');
};
};
Basically I am trying to update the table user at user_ip row with value ip_user, if user_ip field is empty of course.
So nothing updating and the user_ip filed remains empty please help.
There are two things I can see on your script.
you are using if($get_ip['user_ip']== '') statement, which will insert data when $get_ip['user_ip'] is only empty or it will ignore to insert data when $get_ip['user_ip'] have some data.
You are using SET user_ip='$user_ip' on update query, I may not be correct, however I assume that you are trying to store data from $get_ip['user_ip'], if this is the situation use SET user_ip='$get_ip['user_ip']' instead of SET user_ip='$user_ip' on your insert query.
if($get_ip['user_ip']== '')
won't work except if $get_ip['user_ip'] is empty.
use
if(!empty($get_ip['user_ip']))
instead
There are just soooo many things wrong here, but in the interest of being helpful:
Assign the query string to variable rather than directly injecting it into the mysql_query function. Then, echo this string out. This will show you want you are sending to the database. Copy that output somewhere, and then log into whatever you use to manage your database (I assume it'll be phpMyAdmin). Open up your database and then the table you're targeting, and then use the query editor to run your query (paste the output you copied earlier).
If your query string isn't what you expected, you have a code error.
If your query is as you expected, and runs in the database tool, you
likely have a permissions issue with the user account you're using in
your connection string.
If your query is as expected, but doesn't run correctly in your
database tool, your problem most likely is a schema error.

Categories