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
Related
I am trying to build an SQL query that will insert the check-in time for a child at a fictional daycare facility. Here is a condensed version of my query code:
$childFirstName = $_POST['childFirstName'];
$childLastName = $_POST['childLastName'];
$now = new DateTime();
$nowDate = $now->format('m-d-Y');
$nowTime = $now->format('h:i');
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$sql = "INSERT INTO checkinout(date, in, child_id) VALUES(?,?,?)";
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $nowDate);
$statement->bindValue(2, $nowTime);
$statement->bindValue(3, $row['id']);
$statement->execute();
The checkinout table uses VARCHAR datatypes for the date and in columns. Originally they were set to use DATETIME, but I received the same errors.
Right now I get the following errors returned...
You can see from the error messages that my values are getting passed in the way I want them to, but I don't understand where my syntax error would be.
Enclose your field names with backticks. Two of them are reserved words (date and in):
$sql = "INSERT INTO checkinout(`date`, `in`, `child_id`) VALUES(?,?,?)";
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.
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);
I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli
I am looking for some guidance.
I have a data form field which I am inserting into a table and am looking to association the data with the id's of other relevant data. I was wondering if there was recommended way to insert an array of relevant Id's in relation to the information I am referring too.
Below is what Im thinking...
Eg. php reads
<?php
$name = $_POST['name'];
$info = $_POST['information'];
$id = $_POST['id'];
$family = array();
?>
<?php
$select = "SELECT *
FROM `names_family`
WHERE `name` LIKE '$name'
LIMIT 0 , 30";
$selected = mysql_query($select, $connection);
if(!$selected){
die("Hal 9000 says: Dave the select family name ID query failed " . mysql_error());}
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
array_push($family, $familyName => $familyId);
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";
$insertedInfo = mysql_query($insertInfo, $connection);
if(!$insertedInfo){
die("Hal 9000 says: Dave the insert info query failed " . mysql_error());}
?>
Is this a recommended way to relate information? Or is another way to achieve the same result?
What data type is the "family" column in MySQL?
I'm pretty sure you can't straight up insert php arrays like that into MySQL.
If it's possible, guess it's one of those things I didn't know because I never even tried.
The easiest way to do this is to encode your php array into a JSON string and decode it back into a php array when you read it.
$family = array();
...
$familyJsonString = json_encode($family);
...
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$familyJsonString');";
...
$queryString = "SELECT * FROM family_info WHERE name = '$someName'";
$query = mysql_query($queryString, $connection);
$familyData = mysql_fetch_assoc($query);
$decodedFamilyArray = json_decode($familyData['family']);
where the family column should be a varchar or text type depending on how long the family array gets.
A more robust way to do this is to create a separate table to store your family data and use a MySQL JOIN statement to get the values associated to one entry in the family_info table.
here is some info on joins
Joining two tables without returning unwanted row
http://dev.mysql.com/doc/refman/5.0/en/join.html
there is another way
$family=array()
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
$family[]=$familyName.$familyId;
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";