Can''t insert into table - php

The intended purpose of this script is to add an item to something that resembles a shopping cart. when the user clicks a button the script below should load.
the script starts by getting the product id for the product name that has been entered in a form.
this is then put into a variable.
The INSERT query is then performed, using the LAST_INSERT_ID() method to the ID of the last order that was added
if(isset($_GET['submit1']))
{
$db_product_name = $_GET['product_name'];
$query = "SELECT ProductID FROM product WHERE Product_Name = '$db_product_name'";
$result = mysql_query($query)
or die(mysql_error());
$fetch = mysql_fetch_assoc($result);
$db_productid = $fetch['ProductID'];
$query = "INSERT INTO `the_shop`.order_line_item(
`OrderID`
`ProductID`
)
VALUES (
`LAST_INSERT_ID()`, `$db_productid`)";
$result = mysql_query($query)
or die(mysql_error());
}
However I get the following error:
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 'ProductID ) VALUES (
LAST_INSERT_ID(), ..)' at line 3

You have missed comma after OrderID
INSERT INTO `the_shop`.order_line_item(
`OrderID`, -- <---- here is a missed comma
`ProductID`
)
Mysql always points to a part of the query it cannot parse. It means that syntactic error occurred right before the cited part

Related

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: 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 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

Trouble Taking a company name from one table an inserting it to another

Hi I have a table full of company names, the problem I am having is that it is full of duplicates.
To resolve this I am using the following piece of code to remove the data from one table and then insert it in to another using DISTINCT.
When i run the code, i keep getting the following error,
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 's Group Holdings Ltd')' at line 4
If i remove the company name variable it inserts all of the ip address fine, but as soon as i try to insert a company name i get the above error.
$query = "SELECT DISTINCT ip_address, company_name, FROM companydetail1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$ip_address = $row['ip_address'];
$company_name = $row['company_name'] ;
mysql_real_escape_string($company_name);
mysql_real_escape_string($ip_address);
mysql_query("INSERT INTO companydetail30 (ip_address, company_name) VALUES ('$ip_address', '$company_name') ") or die(mysql_error());
}
Any suggestions would be appreciated.
Thanks
Not only does your code not work in its current state, it is also vulnerable to SQL injection because you are using mysql_real_escape_string incorrectly.
The mysql_real_escape_string function gives back the escaped string as its return value, so you need to assign it back to the variable to save the escaped string:
$company_name = mysql_real_escape_string($company_name);
$ip_address = mysql_real_escape_string($ip_address);
in your query with distinct there ia an error
$query = "SELECT DISTINCT ip_address, company_name, FROM companydetail1";
there is a "," after company_name it should not be
query should be like this
$query = "SELECT DISTINCT ip_address, company_name FROM companydetail1";
Secondly you should do like this.
$company_name = mysql_real_escape_string($company_name);
$ip_address = mysql_real_escape_string($ip_address);

MYSQL Query error WHERE id = $id

I'm creating and then editing a row in a table, however my edit mysql query in php is giving me an error that I can't figure out. Any help?
The creation query:
$query = "INSERT INTO timelines (
id, event_name, event_date, date_created, attendee_count, attendee_names, maximum_attendees, creator_id, creator_name, price, thumbnail
) VALUES (
'{$timelineID}', '{$event_name}', '{$event_date}', '{$date_created}', '{$attendee_count}', '{$attendee_names}', '{$maximum_attendees}', '{$creator_id}', '{$creator_name}', '{$price}', '{$thumbnail}'
)";
The edit query:
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}',
WHERE id = {$timelineID}";
Error:
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 id =' at line 8
you have an extra comma before the WHERE clause. just remove it and it will work fine.
thumbnail = '{$thumbnail}',
^ here
WHERE ...
final query,
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}'
WHERE id = {$timelineID}";
Your query is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it.
How can I prevent SQL injection in PHP?

MySQL UPDATE gives error

I have tried for hours now to update a MySQL table with PHP.
I used the following code (and several others) but it gives an error message:
$id = $_GET['id'];
if(isset($_POST['descr'])){
$go = $_POST['descr'];
mysql_query("UPDATE Rooms SET Desc='$go' WHERE Room_ID='$id'")
or die(mysql_error());
}
mysql_close($conn);
with the error: "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 'Desc='This room is the primary test-room. It is?' WHERE Room_ID='11'' at line 1"
The form is called: "descr", the table "Rooms", the field that needs update is "Desc" and it should be where the corresponding ID is, based on a dynamic URL.
If I write echo = $go it outputs the correct data, so I suppose it's the php.
It DOES connect correctly to the database.
Desc is a special word in mysql
try it by escape
mysql_query("UPDATE Rooms SET `Desc`='$go' WHERE Room_ID='$id'")
Assuming that ID is a number:
$id = $_GET['id'];
if(isset($_POST['descr'])){
$go = $_POST['descr'];
mysql_query("UPDATE Rooms SET `Desc`='".$go."' WHERE Room_ID=".$id.")
or die(mysql_error());
}
mysql_close($conn);
Desc is reserved for ORDER BY! Enclose it with '`' symbols!
mysql_query("UPDATE `Rooms` SET `Desc` = '".$go."' WHERE `Room_ID` = ".$id.")
or die(mysql_error());

mysql_fetch_array error when using WHERE clause

Im using:
$query = "SELECT * FROM mydb WHERE condition = New ORDER BY id ASC";
but i get this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mydb.php on line 84
however if i remove the where clause it works perfectly, can anyone point me in the right direction?
Is the Where clause not usable when doing a fetch array?
Thanks for any help.
edit: error message I've got:
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 'condition = 'New' ORDER BY id ASC'
always run all your queries this way (at least until you adopt some intelligent lib for this)
$query = "SELECT * FROM mydb WHERE condition = New ORDER BY id ASC";
$result = mysql_query($query) or trigger_error(mysql_error()." in ".$query);
just because not a single soul in the world can tell what's wrong with your query, but database itself. So, you have to ask it if there were any trouble. Not stackoverflow community (they have no idea anyway) but your db server. That's the point.
Note that you have to be able to watch errors occurred, either on-screen or in the error log.
After getting error message about syntax error you have to check syntax of the displayed query. If there are no visible errors, refer to http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html in case there are reserved word unescaped in your query. condition seems is. So
$query = "SELECT * FROM mydb WHERE `condition` = New ORDER BY id ASC";
will be solution
You appear to be missing quotes around the word "New".
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
Also, are you passing $query to mysql_fetch_array, or did you just not mention the mysql_query call in your question?
Since you have tried adding single quotes to the ('New'),
kindly ensure that the condition is a column in the table you are querying and
that mydb is a table in your database (and not your database name)!
You have to quote the string.
$query = "SELECT * FROM mydb WHERE `condition` = 'New' ORDER BY id ASC";
Edit:
condition is a reserved word.
Is New one of your columns or just a value?
Try this:
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
$result = mysql_query( $query );
while( $row = mysql_fetch_array( $result ) {
// use $row
}
Never assume that a query will work - expect errors and check for them before processing any results.
$query = 'SELECT * FROM `mydb` WHERE `condition` = "New" ORDER BY `id` ASC';
$result = mysql_query( $query );
if( !$result ){
// Query Failed. You can access the error details with mysql_error()
}elseif( mysql_num_rows( $result )==0 ){
// Query Returned No Results
}else{
while( $r = mysql_fetch_assoc( $result ) ){
// Do whatever you want with the row, which is $r
}
}

Categories