update query is not working in php mysql - php

my query is:
$q = mysql_query("UPDATE `payment_details` SET `txnid`='$txnid',`amount`='$amount',`email`='$email',`firstname`='$firstname',`phone`='$phone',`productinfo`='$productinfo' where `id`='$id' ") or die(mysql_error());
but is is working when i change id = "1";
please any one can help with this problem.

The function mysql_query is deprecated in php 5.5.
Also it`s not very cool to put values in database like that.
You can use php PDO and bind values
Use the bindParam and prepare in the PDO to prevent SQL injection.

First of all check if $id has a value or not with var_dump($id);
Second thing is that don't put your variables inside single quotes otherwise it will be considered as a string.You need to concatenate your variables or you can use curly braces which serve as a substitution for concatenation, they are quicker to type and code looks cleaner.
Try this:-
$q = mysql_query("UPDATE `payment_details` SET `txnid`='{$txnid}',`amount`='{$amount}',
`email`='{$email}',`firstname`='{$firstname}',`phone`='{$phone}',`productinfo`='{$productinfo}'
WHERE `id`='{$id}' ") OR die(mysql_error());
It will work fine.

You should check the value of $id first and go from there.
var_dump($id);
If you get null or empty, there is your problem. If you get a non empty value, try to run the query in your mySQL client with the value that you got.
Also, it would help to see the error message that you are getting :)
Good luck.

Related

Why is my data not stripping properly with mysql_real_escape_string?

Here is my code below:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
//Finally, we can actually the field with the student's information
$sql = <<<SQL
UPDATE `database` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '{$studentTalking}',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
I am trying to use the mysql_real_escape_string to allow apostrophes entered into our form by the user to go to the database without breaking the database, however the data will either go through as null or the apostrophe will break the database. I have changed everything I could think of, and can't figure out why this isn't working. Yes I understand the that injections could break our database, and we will work on updating the code soon to mysqli but we need this working now. I suspect my syntax isn't correct and the first line may need to be moved somewhere, but I am not the strongest in PHP and I am working with code that was written by previous interns. Thank you in advance.
Switch to mysqli_* functions is the right answer.
The answer if intend to stayg with the deprecated and dangerous mysql_* functions:
Here you set a new variable equal to your escaped $_POST[]:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
But in your SQL you still refer to the $_POST array... Switch your SQL over to use your new variable you created
$sql = <<<SQL
UPDATE `tgtw_rsvp` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '$studentTalking',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
Because you are not using the stripped variable but still the raw POST data.

One SQL statement to deal with both NULL and a STRING possibility for same value

I have a strange situation I have never run into before.
I am calling data from an API and updating my database to match exactly. An issue arises when the value comes back NULL.
My SQL statement:
$update_entry = "UPDATE clientpatientrelationships SET APILastChangeDate=$APILastChangeDate WHERE Id='$Id'";
The reason I have no quotes around the $APILastChangeDate variable, is because to use NULL, I cant use single quotes. But when the value is a string, it needs the quotes. Here lies my issue. Also, part of my issue is the need for triple equal sign when setting a variable to NULL.
I can get each of the following individual statements to work one at a time:
$APILastChangeDate="'0000-00-29 00:00:00'";
$update_entry = "UPDATE clientpatientrelationships SET APILastChangeDate=$APILastChangeDate WHERE Id='$Id'";
And
$APILastChangeDate===NULL;
$update_entry = "UPDATE clientpatientrelationships SET APILastChangeDate=$APILastChangeDate WHERE Id='$Id'";
With out the triple equal sign, the NULL value will not work when inside a variable. But, with triple quotes, the string value will not work.
I am trying to write a single function to handle all of this, but I cant figure out the === along with the quotes or no quotes.
My function:
function null_test($value)
{
if (is_null($value)){
return NULL;
} else {
return "'".$value."'";
}
}
Since the value coming back from the API might be NULL or, say, 25 - I cant figure out how to write a single function with a single update statement to handle this.
The only way I have gotten this to work is to use two different update statements with an IF clause to test if(is_null($value)).
I have done research on google, but to no avail. Is it possible to handle both a NULL or a string in one SQL statement?
I worked with php some years ago, when I built queries, I always used sprintf, it's a good way to build queries in php and you can use str_replace to replace the value 'NULL' for NULL. You have to do something like this:
$arrayNulls = ("'null'", "'NULL'");
$query = sprintf ("UPDATE clientpatientrelationships SET APILastChangeDate='%s' WHERE Id='%s'", $APILastChangeDate, $Id);
$query = str_replace($arrayNulls, "NULL", $query);
I hope this information helps you.
Good Luck.

concatenate mysql select query with php variable?

I am trying to concatenate a MySQL SELECT query with PHP variable but got an error.
My PHP statement which gives an error is:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);
and error as:
( ! ) Notice: Undefined variable: info in C:\wamp\www\pollBook\poll\login.php on line 18
Call Stack
I don't understand where I missed the code.
When I write query without WHERE clause it works fine.
The reason why your code isn't working
You are attempting to use a variable, $info, that has not been defined. When you attempt to use an undefined variable, you're effectively concatenating nothing into a string, however because PHP is loosely typed, it declares the variable the second you reference it. That is why you're seeing a notice and not a fatal error. You should go through your code, and ensure that $info gets a value assigned to it, and that it is not overwritten at some point by another function. However, more importantly, read below.
Stop what you are doing
This is vulnerable to a type of attack called an SQL Injection. I'm not going to tell you how to concatenate SQL strings. It's terrible practice.
You should NOT be using mysql functions in PHP. They are deprecated. Instead use the PHP PDO Object, with prepared statements. Here's a rather good tutorial.
Example
After you've read this tutorial, you'll be able to make a PDO Object, so I'll leave that bit for you.
The next stage is to add your query, using the prepare method:
$PDO->prepare("SELECT * FROM tbl WHERE `id` = :id");
// Loads up the SQL statement. Notice the :id bit.
$actualID = "this is an ID";
$PDO->bindParam(':id', $actualID);
// Bind the value to the parameter in the SQL String.
$PDO->execute();
// This will run the SQL Query for you.
You are missing space before "AND " and you should use single quotes as suggested in other answers.
$result=mysql_query("SELECT user_id,username,add FROM users WHERE *username =".$user."AND* password=".$add);
Updated:
echo $sql = "SELECT user_id,username,add FROM users WHERE username ='".$user."' AND password='".$add."'";
$result=mysql_query($sql);
although there is no $info variable used in the query but you need to correct the query:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username ='" . $user . "' AND password='" . $add . "'");
First from the error its looks like one of your variables is not defined. .. check it. Second surround your parameters with ' for safer syntax.
This is because the variables you are using might not have defined above
So first initialize your variables or if its coming from somewhere else(POST or GET) then check with isset method
So complete code would be
$user = 123; // or $user = isset($user)?$user:123;
$add = 123456; // or $add = isset($add)?$add:123456;
And then run your query
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);

php mysql_query returns nothing after insert (and nothing is inserted either)

I've got the following code:
<?php
if(!empty($error_msg))
print("$error_msg");
else
{
require_once("../include/db.php");
$link = mysql_connect($host,$user,$pass);
if (!$link)
print('Could not connect: ' . mysql_error());
else
{
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
$res = mysql_query($sql);
print("$sql<br>\n");
print_r("RES: $res");
mysql_close($link);
}
}
?>
In one word: it does not work. mysql_query doesn't return anything. If I try the same
query within php_myadmin, it works. It does not insert anything either. Also tried it as
user root, nothing either. Never had this before. Using mysql 5.1 and PHP 5.2.
Any ideas?
mysql_query will return a boolean for INSERT queries. If you var_dump $res you should see a boolean value being printed. It will return TRUE for a successful query, or FALSE on error. In no cases it ever returns NULL.
In addition, never pass input data (e.g.: $_POST) directly to an SQL query. This is a recipe for SQL injection. Use mysql_real_escape_string on it first:
$language = mysql_real_escape_string($_POST['language']);
$sql = "INSERT INTO language SET language='$language'";
And don't forget to quote your array indices (e.g.: $_POST['language'] instead of $_POST[language]) to prevent E_NOTICE errors.
You need to specify a database so the system knows which database to run the query on...
http://php.net/manual/en/function.mysql-select-db.php
Without selecting a database, your data will not be inserted
mysql_query returns a boolean for INSERT queries. If used in string context, such as echo "$res", true will be displayed as 1 and false as an empty string. A query error has possibly occured. Use mysql_error() to find out why the query has failed.
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
This is very bad practise, as a malicious user can send crafted messages to your server (see SQL Injection).
You should at least escape the input. Assuming your column names are named 'language' and 'country_code', this is a better replacement for the above code:
$sql = sprintf('INSERT INTO LANGUAGES (language, country_code) VALUES ("%s","%s")',
mysql_real_escape_string($_POST['language']),
mysql_real_escape_string($_POST['country_code'])
);
For a description of the mysql_real_escape_string function, see the PHP Manual. For beginners and experienced programmers, this is still the best resource for getting information about PHP functions.
Instead of using $_POST directly, I suggest using the filter_input() function instead. It's available as of PHP 5.2.
With an INSERT query, mysql_query returns true or false according as the query succeeded or not. Here it is most likely returning false. Change the line print_r("RES: $res"); to print_r("RES: ".(int)$res); and most likely you will see it print RES: 0.
The problem may be that MySQL expects a list of column names before the VALUES keyword.
Also, you appear to be inserting POST variables directly into SQL - you should read up on SQL injection to see why this is a bad idea.
--I retract the quote comment, but still not good to directly insert $_POST values.--
Second, I don't think i've seen print_r quite used like that, try just using an echo.
And mysql_query is only expected a boolean back on an INSERT, what are you expecting?
Now ive got this:
$language = mysql_real_escape_string($_POST['language']);
$country_code = mysql_real_escape_string($_POST['country_code']);
$sql = "insert into shared_content.languages (id,language,country_code) values(NULL,$language,$country_code);";
$res = mysql_query($sql);
print("$sql<br>\n");
var_dump($res);
print(mysql_error());
mysql_close($link);
And the output:
insert into shared_content.languages (id,language,country_code) values(NULL,NETHERLANDS,NL);
bool(false) Unknown column 'NETHERLANDS' in 'field list'

Sql query problem

I have the below sql query that will update the the values from a form to the database
$sql=
"update leads set
category='$Category',
type='$stype',
contactName='$ContactName',
email='$Email',
phone='$Phone',
altphone='$PhoneAlt', mobile='$Mobile',
fax='$Fax',
address='$Address',
city='$City',
country='$Country',
DateEdited='$today',
printed='$Printed',
remarks='$Remarks'
where id='$id'";
$result=mysql_query($sql) or die(mysql_error());
echo '<h1>Successfully Updated!!.</h1>';
when i submit I dont get any errors and the success message is displayed but the database isnt updated . When i echo the $sql, all the values are set properly. and when i ech the $result i get the value 1.
can someone please tell me what am i doing wrong here??
Have you tried running the echo of $sql directly using some DB tool? It may provide a more informative error. Alternatively, if that works you may have an issue where the transaction isn't being committed. Often a connection is set to automatically commit transactions, but that may not be the case here. Try adding a commit.
And have you ever heard of SQL injection attacks?
If you have a query that is not giving the expected result or receiving an error, and the problem isn't obvious, you should generally take a look at the final query just before it's run. Try using this right before running the query:
echo $sql;
exit;
Viewing the actual query often makes it obvious what the problem is, especially when the query includes variables. If the problem still isn't obvious, you can paste the query as is into a query browser to get feedback directly from the database engine.
Interestingly, using parametrized queries, you won't get to see the parameter values, as the parameters get replaced by MySQL, not PHP, however, you'll still get to see the entire prepared query.
Also, you can see the number of affected rows from your UPDATE statement with the mysql_affected_rows() function. You could put this immediately after the query is run:
echo ("Updated records:", mysql_affected_rows());
Spaces are often forgotten when concatenating queries.
$sql = "SELECT * FROM ducks";
$sql .= "WHERE duck = 'goose'";
When echoing the above query, we see:
SELECT * FROM ducksWHERE duck <> 'goose'
I'm guessing that the WHERE clause in your UPDATE statement isn't matching an "id = '$id'".
Also, is the id column really a string? You've put single quotes around the value. MySQL will cast the string to an integer if needed, but if it's an integer, save the database some work and remove the single quotes.
try to echo $sql and run it directly in any database console, may be there is no record with id = $id
SQL Injection can be the answer. Not an intentional attack (at this moment), but if your parameters have some unexpected information like quotes or other reserved characters you can have strange results. So, try to run this SQL directly in your database administration utility.
Try doing this
"""update leads set
category="$Category",
type="$stype", etc...; """
See if that works

Categories