Make a single insert statement - php

I have a mysql table named stock sales which have 3 column, I want insert data with a single statement.
"INSERT INTO stock_sales (size) SELECT size FROM stock_avail WHERE id='5957';
"INSERT INTO stock_sales (transactionid, date) VALUES ('$bill','$date')";

$sqlQuery = "INSERT INTO stock_sales (size) SELECT size FROM stock_avail WHERE id='5957';";
$sqlQuery. = "INSERT INTO stock_sales (transactionid, date) VALUES ('$bill','$date')";
mysqli_multi_query($con,$sqlQuery);
The mysqli_multi_query() function performs one or more queries against
the database. The queries are separated with a semicolon.
For more info, please click Mysqli_Multi_Query - W3 Schools

Try:
INSERT INTO stock_sales (size, transactionid, date)
SELECT size, '$bill', '$date'
FROM stock_avail
WHERE id='5957'
or
INSERT INTO stock_sales (transactionid, date, size)
VALUES ('$bill', '$date', (SELECT size FROM stock_avail WHERE id='5957'))

Related

SQL query will fail with actual data but will work with test data

So, im trying insert some data into a table, I get the previous data from either GET or another SQL query (My database consists of INT and TEXT so I don't think there is an issue there).
I have a query
$sql2 = "INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS)
VALUES ('$user_name','$user_id','$artist_id','$artist_name','$price','$description','$comments')";
This $sql2 echo's as follows
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')
However, when I do
if ($conn->query($sql2) === TRUE) {
$conn->close();
echo "success";
exit();
} else {
$conn->close();
echo "failed";
}
I get failed printed. But if I change the $sql2 into
VALUES ('test','test','test','test','test','test','test')";
The query is executed successfully inserted into my database (other than the int values that turn into 0). Could someone enlighten me why this would happen?
for some reason your artist_id value has a double quotation mark while other values has single quotation mark, which is probably the reason your query fails( i have bolded it):
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')

MYSQL insert values with select

I'm trying to insert values like this:
$sql = "INSERT INTO daily_food (number, weight, title, price) VALUES ('1', SELECT weight, title, price FROM food where title = '$add_food' LIMIT 1)";
mysqli_query($conn, $sql);
I have database with food which i'm selecting from. I would like to insert that number aswell but code is doing nothing. I'm new in sql so i can't figure out how the code should look.
Just use insert . . . select, values is not necessary:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = '$add_food'
LIMIT 1;
Im assuming that number is, indeed, a number, so quotes are not needed.
In addition, you should be passing in $add_food as a parameter, something like this:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = ?
LIMIT 1;

How do I combine these two queries into a single INSERT INTO?

Can someone tell me how can I combine these two queries into a single INSERT INTO query?
$query1 = "INSERT INTO `monthly_income`(`Year`, `Month`) VALUES (2017, 'September')";
$query2 = "INSERT INTO `monthly_income`(`totalincome`) SELECT SUM(Income) FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";
Here I want to insert all those values into a single row in the table "monthly_income". In Query2, i generate the total income between two dates from a seperate table called "eventincome". The "monthly_income" table has columns [Year, Month, totalincome]. And the "eventincome" table has columns [eventDate, eventTitle, Earnings, Expenses, Income]. So how can I join these two querys to use it in a
mysqli_query($conn, parameter)
:)
PS: I want to set those values from those queries in the same row, without creating two seperate rows becuse of those two INSERT INTO's. That's why I wanna join/combine/merge(whatever) those two queries :)
Give this a try
$query2 = "INSERT INTO `monthly_income`(`totalincome`,`Year`, `Month`) SELECT SUM(Income),2017 as Year, 'September' as Month FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";
Add the values from the first query as constants in the second query...
"INSERT INTO monthly_income(Year, Month,totalincome) SELECT 2017, 'September',SUM(Income) FROM eventincome WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-3'";

How to update the SQL table

I am looking to insert the web_salescart table:
$insert_row = $conn->query(
"INSERT INTO web_salescart (cartnumber, branchcode, stockid, qty, price, descr, salesman, date, time, brname,discount)
VALUES ('".$_SESSION['CART']."', '".$_SESSION['BRANCHCODE']."', '".$item_data['stockid']."', '".$item_data['qty']."', '".$item_data['unit_price']."', '".mysql_real_escape_string($item_data['description'])."', '".$_SESSION['salescode']."', '".date("m-d-y")."', '".date("g:i a")."', '".mysql_real_escape_string($_SESSION['BRNAME'])."','".$item_data['discount']."')");
Here $item_data['discount'] is updating 33%. I need to update it as 0.33 in web_salescart table and 33% is the display figure. Can I use an update statement right after the INSERT so that $item_data['discount'] is divided by 100?
Convert it to 0.33 when you insert it, not as a separate query. In the query, replace $item_data['discount'] with:
number_format(str_replace('%', '', $item_data['discount'])/100, 2)

PHP/SQL After insert value to table and set one value as unique, no more values can be inserted

I try to create normalized db.
When I insert values FIRST time, everything is working perfectly, but (I think cause of set values as UNIQUE) it do not want to add.
This is my queries ( I can show database as well if needed )
$query = "INSERT INTO userMore (userEmailG, userGenderG, userAboutG, userBirthdayG, userLanguageG) values ('$userEmailG','$userGenderG', '$userAboutG', '$userBirthdayG', '$userLanguageG');";
$query .= "INSERT INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT INTO dvlaInfoMore (sixMonthRate, twelveMonthRate, wheelPlan, revenueWeight, typeApproval, taxStatus, taxed, taxDetails, mot, motDetails) values ('$sixMonthRate', '$twelveMonthRate', '$wheelPlan', '$revenueWeight', '$typeApproval', '$taxStatus', '$taxed', '$taxDetails', '$mot', '$motDetails');";
$query .= "INSERT INTO dvlaInfoBasic (id_uDInfoM, plateNumber, make, model, yearOfManufacture, cylinderCapacity, dateofFirstRegistration, co2Emissions, fuelType, colour, vin, transmission)
values (LAST_INSERT_ID(), '$plateNumber', '$make', '$model', '$yearOfManufacture', '$cylinderCapacity', '$dateofFirstRegistration', '$co2Emissions', '$fuelType', '$colour', '$vin', '$transmission');";
$query .= "INSERT INTO userLocation (latitude, longitude, postCode) values ('$latitude', '$longitude', '$postCode');";
$query .= "INSERT INTO userChioce (doWithCar) values ('$doWithCar');";
$query .= "INSERT INTO userStatus (userIdG) values ('$userIdG');";
$query .= "INSERT INTO userMain (userIdG, id_uB, id_uDInfoB, id_uChoice, id_uLoc, id_uStat) values ('$userIdG', (SELECT id_uB FROM userBasic WHERE userEmailG='$userEmailG'), (SELECT id_uDInfoB FROM dvlaInfoBasic WHERE plateNumber ='$plateNumber'), LAST_INSERT_ID(), (SELECT id_uLoc FROM userLocation WHERE postCode='$postCode'),(SELECT id_uStat FROM userStatus WHERE userIdG='$userIdG'))";
So, first time userMore added then userBasic then dvlaInfoMore then dvlaInfoBasic and so one
I set in userBasic column userNameG as UNIQUE, so IF inserted email which already exist, it do not want to go further, BUT if not, everything added correctly.
ALL what I want that it will continue inserting different cars and then by using existing email display result in table userMain.
P.S. if I try to add different car from by using same email address it doesn't work., basically do not add anything.
As you suspected yourself, INSERT with an existing key defined as UNIQUE will fail.
One workaround is to use the REPLACE INTO statement instead of INSERT (see manual).

Categories