Query Not Working - php

The simple query below is not working. Any idea why? When I echo the three variables, the correct values are returned, so I know I have variables.
Thanks in advance,
John
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
echo $comment;
echo $uid;
echo $subid;
mysql_connect("mysqlv12", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);

The query looks fine on the surface. What are the values you're inserting? Do any of them have a single quote in them? I'd guess the comment field is the likeliest culprit for that. Your code is utterly vulnerable to SQL injection as it stands now. You should replace all the variable assignments as follows, for a bare minimum of security:
$comment = $_POST['comment'];
becomes
$comment = mysql_real_escape_string($_POST['comment']);
This will also incidentally take care of any single quotes that may be causing your query to fail. As well, you do need to check if the query succeeded:
mysql_query($query) or die (mysql_error());
which would immediately tell you if there were any problems (sql syntax error, database server died, connection failed, etc...)

Related

mysql cyrillic troubleshooting

Hi guys!
So, I have one question: I have some data which is cyrillic. Here is the problem:
Incorrect string value: '\xD0\xBD\xD0\xBE\xD0\xB2...' for column 'title' at row 1.
Here is my code:
$link = mysql_connect('localhost', 'root', 'pass');
if($link&&isset($_POST['addSticker'])){
$title = $_POST['title'];
$description = $_POST['description'];
$photo = mysql_real_escape_string(urlencode($_POST['photo']));
$quantity = $_POST['quantity'];
$price = $_POST['price'];
mysql_select_db('db_name');
$sql = "INSERT INTO table (title, description, photo, quantity, price) VALUES ('$title', '$description', '$photo', '$quantity', '$price');";
mysql_query("SET NAMES utf8", $link);
mysql_query($sql, $link) or die(mysql_error());
}
Thanks for any help.
First thing is that your query is vulnarable to SQL injections. It is recommended to escape your characters (MySQLi). This might even solve your problem. The second thing is you're still using mysql API which is deprecated. Instead, you should switch to PDO or mysqli API. In case you have bad collation (escaping input doesn't help), you can also change MySQL collation to one of these so that database can understand these characters.

Query Failed!You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I am trying to put this into the database. And I am getting an unexpected error, however, saying:
Query Failed! 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 'order(Order_Date,Order_Time,Delivery_Charge,Delivery_Fname,Delivery_Lname,Delive' at line 1.
Here's my PHP:
<?php
//error_reporting(E_ERROR | E_PARSE);
include("includes/db.php");
include("includes/functions.php");
if($_REQUEST['command']=='update')
{
$date = date('Y-m-d');
$time = time('H:i:s');
$charge = $_REQUEST['ocharge'];
$fname = $_REQUEST['ofname'];
$lname = $_REQUEST['olname'];
$mobile = $_REQUEST['omobile'];
$add1 = $_REQUEST['oadd1'];
$add2 = $_REQUEST['oadd2'];
$postcode = $_REQUEST['opostcode'];
$state = $_REQUEST['ostate'];
$country = $_REQUEST['ocountry'];
$weight = $_REQUEST['oweight'];
$credit = $_REQUEST['ocredit'];
$pin = $_REQUEST['opin'];
$city = $_REQUEST['ocity'];
$result=mysql_query("insert into order(Order_Date,Order_Time,Delivery_Charge,Delivery_Fname,Delivery_Lname,Delivery_HP,Delivery_Street1,Delivery_Street2,Delivery_Postcode,Delivery_State,Delivery_Country,Total_Weight,Credit_No,Pin_No,Delivery_City) values ('$date',$time,$charge,'$fname','$lname',$mobile,'$add1','$add2',$postcode,'$state','$country',$weight,$credit,$pin,'$city')");
if($result === FALSE)
{
die("Query Failed!".mysql_error().$result);
}
$orderid=mysql_insert_id();
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++)
{
$pid=$_SESSION['cart'][$i]['productid'];
$q=$_SESSION['cart'][$i]['qty'];
$price=get_price($pid);
mysql_query("insert into order_detail (Order_ID,Product_ID,Order_Quantity,Sub_Total) values ('$orderid','$pid','$q','$price')");
}
die('Thank You! your order has been placed!');
}
?>
What is wrong with the query?
ORDER is a reserved keyword. So, you'll need to escape it in backticks, like so:
INSERT INTO `order` ...
Not using reserved keywords in your query would be the better solution, but escaping them with backticks works, too.
Here's a few debugging tips. Rather than this:
$result=mysql_query("insert into order(Order_Date,Order_Time,Delivery_Charge,Delivery_Fname,Delivery_Lname,Delivery_HP,Delivery_Street1,Delivery_Street2,Delivery_Postcode,Delivery_State,Delivery_Country,Total_Weight,Credit_No,Pin_No,Delivery_City) values ('$date',$time,$charge,'$fname','$lname',$mobile,'$add1','$add2',$postcode,'$state','$country',$weight,$credit,$pin,'$city')");
Always do this:
$sql ="insert into order(Order_Date,Order_Time,Delivery_Charge,Delivery_Fname,Delivery_Lname,Delivery_HP,Delivery_Street1,Delivery_Street2,Delivery_Postcode,Delivery_State,Delivery_Country,Total_Weight,Credit_No,Pin_No,Delivery_City) values ('$date',$time,$charge,'$fname','$lname',$mobile,'$add1','$add2',$postcode,'$state','$country',$weight,$credit,$pin,'$city')";
$result = mysql_query($sql);
This makes it trivial, when working on your code, to also do this:
echo htmlentities($sql);
That will show you the query you are working with (and not the PHP code that builds the query, which may hide awkward characters inside your values).
Finally, consider writing your code like this:
$sql = "
INSERT INTO order (
Order_Date, Order_Time, Delivery_Charge,
Delivery_Fname, Delivery_Lname, Delivery_HP,
Delivery_Street1, Delivery_Street2, Delivery_Postcode,
Delivery_State, Delivery_Country, Total_Weight,
Credit_No, Pin_No, Delivery_City
)
VALUES (
'$date', $time, $charge,
'$fname', '$lname', $mobile,
'$add1', '$add2', $postcode,
'$state', '$country', $weight,
$credit, $pin, '$city'
)
";
$result = mysql_query($sql);
I've upper-cased the SQL and formatted the query to make it readable, so you can be sure you are supplying the right value for the right column. No horizontal scrolling (in your editor or on our screens) is now necessary.
As indicated in the comments, if you take this approach to database inserts, you need to ensure that all of your values are correctly escaped, especially if they come from user input. However, parameterisation is a better way to do this, and note that the "mysql" library is now deprecated.
Addendum: looking at the query, I would say that you need apostrophes around $time, $mobile and $postcode (assuming they are all strings). I presume $charge and $weight are numeric and so therefore do not need quoting.

mysql_query(INSERT ...) function not working in my code

I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.

Form is submitting empty values to database

After being advised that i MUST validate my form so that no-one could hack my database i then made some changes which were adding the mysql_real_string()
$query="INSERT INTO allymccoist (id, firstname, lastname, email, date)
VALUES (NULL, '".$firstname."', '".$lastname."', '".$email."', '".mysql_real_escape_string($new_date)."')";
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
since doing this, nothing is being sent to firstname lastname or email although the date seems to be sending ok though
is thereanything that may be causing this that you can see from my code?
If you're sure that those data actually are set (var_dump your $_POST array to check that),then make sure you have a connection active before using mysql_real_escape_string(), as it would return FALSE otherwise:
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned. If link_identifier isn't defined, the last MySQL connection
is used.
So you can well be entering FALSE in every value.
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')or die(mysql_error());
mysql_select_db('database_name', $link) or die('cannot select database '.mysql_error());
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
You'd be better off altogether by using prepared statements, so you won't have to worry about SQL injections.
Also, I'd advice you against using NULL in your insert query for the field ID. If you're table is strcutred as I can guess, and ID is a primary key with AutoIncrement, you don't need to enter it in your query, as it would be automatically filled by the engine.
For wheter it is better to use prepared statements or mysql_real_escape_string(), check this resource mysql_real_escape_string vs prepared statements
The issue of missing data is likely as Damien suggests. Establish a connection, then use mysql_real_escape_string(). The connection is required in part so that mysql_real_escape_string() can take into account the current character set of the connection.
Also, mysql_real_escape_string() is perfectly safe when used in combination with the sprintf() function (full details on sprintf). Most important with sprintf() is setting the correct type specifier so that values get cast properly. Generally, for integers you will use %d. For floats use %f. And for string and date values use %s.
So for your program the code should look something like (note: as Damien suggests, leave id out of the query):
/* Read form data. */
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$date = $_POST['date']);
/* Your form validation code here. */
/* Your db connection code here. */
/* Setup and run your query. */
$query = sprintf("INSERT INTO allymccoist (firstname, lastname, email, date)
VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstName),
mysql_real_escape_string($lastName),
mysql_real_escape_string($email),
mysql_real_escape_string($date));
$result = mysql_query($query);
/* Check for errors with query execution. */
if (!$result) echo("Query Error! Process aborted.");

PHP form will not post

I have just implemented mysql_real_escape_string() and now my script won't write to the DB. Everything worked fine before adding mysql_real_escape_string():
Any ideas??
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
mysql_send("INSERT INTO list
SET id = '',
name = '$name',
description = '$description',
custid = '$custid' ");
what is that mysql_send function?
what if to change it to mysql_query();
It should be easy to figure out what's going on.
Fist, instead of sending the query you're constructing to the database, echo it out (or log it), and see what you're actually sending to the database.
If that doesn't make it obvious, see what mysql_error() has to say.
mysql_real_escape_string should have a database connection passed as the second argument since it asks the database what characters need to be escaped.
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
$cleanstring = mysql_real_escape_string("my string", $connection);
A typical failure on understanding how to use certain functions...
You're just using mysql_real_escape_string on raw input data. Have you ever heard of santizing / validating input? mysql_real_escape_string does not make sense on numbers. If you've validated a variable to be a number, you don't need to escape it.
mysql_send is an alias for mysql_query right?
Use debug code, add echo mysql_error(); after mysql_send(...).
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
//If you doing Update use this code
mysql_query("UPDATE list SET id = '', name = '$name', description = '$description' WHERE custid = '$custid' ") or die(mysql_error());
//OR if you doing Insert use this code.
mysql_query("INSERT INTO list(name, description, custid) VALUES('$name', '$description', '$custid')") or die(mysql_error());
//If custid is Integer type user $custid instead of '$custid'.
If you are updating the records in the list table based on the custid use the UPDATE command OR if you are insertinf the records into list table use INSERT command.

Categories