Storing date in MySQL - php

I want the date to be added to an orders table I have created, once the user proceeds to checkout. The code I currently has just prints:
"Error: Column count doesn't match value count at row 1"
Here's my code:
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', 'DATETIME: Auto NOW()', NOW() )";
The name and total columns store but the date does not. How can I solve this?

This way:
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW())";

You want to insert data inside customer_id, total, order_date (3 rows) but you are sendig '$name', '$total', 'DATETIME: Auto NOW()', NOW(), FOUR.

Your error means that you that the number of fields does not match the number of values. That seems correct: your query tries to insert 4 values into 3 fields. You'd probably have to rewrite the query to
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW() )";

It looks like you need 3 values: customer_id, total, order_date
but you give 4 :'$name', '$total', 'DATETIME: Auto NOW()', NOW()
Maybe it should look like this:
"INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW() )";

Related

Grab Record ID before during submit and save to another table

I have two tables:
Invoices & Invoices Parts
The reason i'm using two tables is because i dont want to save the invoice parts array into one record on the Invoices table and i dont want to save it into multiple records on the Invoices table.
When i submit the data into both tables, how can i link both tables together with the ID if i dont have the ID yet?
$result = mysqli_query($mysqli, "INSERT INTO invoices(labelwarning, status, todaysdate, todaystime, todaysdatetime, avatar, firstname, lastname, mwaid, nextgenid, manager, manageremail, dispatcher, dispatcheremail, techemail, tag, serialnumber, currentequipment, company, address, city, state, zip, contactperson, contactnumber , currentdate, timearrived, timecompleted, login_id) VALUES('$labelwarning', '$status', '$todaysdate', '$todaystime', '$todaysdatetime', '$avatar', '$firstname', '$lastname', '$mwaid', '$nextgenid', '$manager', '$manageremail', '$dispatcher', '$dispatcheremail', '$techemail', '$tag', '$serialnumber', '$currentequipment', '$company', '$address', '$city', '$state', '$zip', '$contactperson', '$contactnumber ', '$currentdate', '$timearrived', '$loginId')");
$result2 = mysqli_query($mysqli, "INSERT INTO invoiceparts(partnumber, partdescription, partprice, partquantity, partdb, login_id) VALUES '$partnumberstring', '$partdescriptionstring', '$partpricestring', '$partquantitystring', '$partdbstring', '$loginId')");
If you need to link the "login_id" and the login_id is generated with AUTO_INCREMENT then you can do it by
for Mysqli connection, mysqli_insert_id($mysqli);
for PDO connection, $mysqli->lastInsertId();
If the login_id is not an AUTO_INCREMENT field then you can do it by
SELECT login_id FROM invoices ORDER BY login_id DESC LIMIT 1;
It'll return the last inserted row from there we can fetch the login_id

Xampp - Column count doesn't match value count at row 1

$query = "INSERT INTO clients(ID_Client,Upgrade,Nome,Email,Cod_Postal,Localidade,Contacto,NIF,Factura,Data_Factura,N_Serie,Codigo,Marca,Modelo) VALUES (NULL,'$Upgrade',
'$Nome',
'$Email',
'$Cod_Postal',
'$Localidade',
'$Contacto',
'$NIF',
'$Factura',
'$N_Serie',
'$Data_Factura', ".$N_Serie.",
'$Codigo',
'$Marca',
'$Modelo')";
What it's wrong about this ? I got the same number of fields / values ..
You've got '$N_Serie', twice, remove the first one.
Columns matching values below:
$query = "
INSERT INTO clients(
ID_Client,
Upgrade,
Nome,
Email,
Cod_Postal,
Localidade,
Contacto,
NIF,
Factura,
Data_Factura,
N_Serie,
Codigo,
Marca,
Modelo
) VALUES (
NULL,
'$Upgrade',
'$Nome',
'$Email',
'$Cod_Postal',
'$Localidade',
'$Contacto',
'$NIF',
'$Factura',
'$Data_Factura',
'$N_Serie',
'$Codigo',
'$Marca',
'$Modelo'
)";

If value exists in table 1 insert into table 2 mysql

For my ordering system, when an admin inserts an order i need to check if the customer he inserts for the order exists in my customer table.
Im trying something like this, but with no luck..
$sql = "IF EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')
THEN insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
Error: syntax error in first line.
What is wrong here?
And is this the right approach? Is there a better way?
you might want to do it "backwards" - insert if exists:
$sql = "insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
select '$customer', '$product', '$quantity', now(), '$note', '$employee'
from dual
where EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')";
Here's a neat trick you can do:
$sql = "INSERT INTO `order`
(`customer_id`, `product`, `quantity`,
`creation_time`, `order_note`, `order_employee`)
SELECT `customer_id`, '$product', '$quantity', now(), '$note', '$employee'
FROM `customer` WHERE `customer_id`='$customer'";
Note that I'm trusting you have already properly sanitised your variables!
But this will only insert the order if the customer with that ID exists.
I think you should think your problem in another way.
Proceed with steps :
1 - I need to know if customer my customer exist?
$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";
2- I try my customer, does he exist?
If(!empty($result_cust)){
$sql = insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
}
With this way your code will be more easily to understand.
Divide and Rule
They said.

Column Count vs Value Count on insert statement - PHP/MySQL

I am working on building an employee database but seem to have run into an interesting issue.
When I run my query to add a new user/employee, I get the error:
Column count doesn't match value count at row 1
From what I have researched, this seems to be an error with inserting more/less values than what is declared in the first part of an insert statement example:
INSERT INTO table (col1, col2) VALUES (val1, val2, val3)
The thing is though, I have looked over my query and the columns and values match perfectly (count wise). I have even looked for things in my query such as missing quotes, commas, etc.
Here is my code (query):
$db->query("INSERT INTO userdata (
Username,
Email,
Phone,
Password,
FirstName,
LastName,
Address,
City,
State,
Zip,
JobTitle,
UserGroup,
JobStatus,
Points,
Status,
BirthDate,
HireDate,
HourlyRate,
DateAdded,
SSN
) VALUES (
'$Username',
'$Email',
'$Phone',
'$Password',
'$FirstName',
'$LastName',
'$Address',
'$City',
'$State',
'$Zip',
'$JobTitle',
'$Group',
'$JobStatus',
0,
'$Status',
'$BirthDate',
'$HireDate',
'$HourlyRate'
'$TodaysDate',
'$SSN'
)") or die(mysqli_error($db));
Some things to note:
This not all of the columns in the table have data inserted here (I think its possible to do this and things such as auto incrementing ID's will fill themselves in and others will be left blank)
From the variable dumps I have done, all of these variables are valid.
I am really confused about this and any help would be appreciated.
Check the following portion again:
INSERT INTO userdata(...,
JobStatus,
UserGroup,
Points,
UserGroup,
Status,
.....
,)VALUES(...,
$JobStatus',
0,
'$Group',
'$Status',
......
)
In values(, ?, ?, ?), after jobstatus, there should be UserGroup and then Points. And UserGroup appeared twice.

SQL Update if already exists, else insert

I have the following sql statement:
$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')";
This is just a basic INSERT sql. Is there a way for it to Update a record if the 'variant_id' is already present. If the 'variant_id' is not already there it should Insert a new one.
Any help would be appreciated
You can check INSERT ... ON DUPLICATE KEY UPDATE
$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')
ON DUPLICATE KEY UPDATE
global_variant_id = VALUES(global_variant_id),
code = VALUES(code),
size = VALUES(size),
details = VALUES(details),
color = VALUES(color),
top = VALUES(top),
price = VALUES(price)";
In MySQL you can use ON DUPLICATE KEY
INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')";
ON DUPLICATE KEY UPDATE `code`=VALUES(`code`);
In T-SQL (2008 an higher) you could use MERGE

Categories