Insert values to mysql from select query - php

I have a php results page which gets values from submited php form like
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
I have an insert query
$sql = "INSERT INTO daily (date, sales) VALUES (CURRENT_TIMESTAMP, '$sales')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
Now i want to add an extra field to db which will be based on a new select query
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
I've tried to add it to insert sql with no result
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$query')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

You could use a insert/select
$sql = "INSERT INTO daily (date, sales, total_sales)
SELECT
CURRENT_TIMESTAMP,
'$sales',
SUM(sales)
FROM daily
WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
in two step you could execute your, query get the value and assign to insert ... eg:
$query = "SELECT SUM(sales) as tot FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
mysqli_query($link, $query) ;
$row = mysql_fetch_array($result, MYSQL_NUM);
$myTotal = $row[0]
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$myTotal')";

You should run that query first, save the results in an array, cycle through the array and add the result in the correct field of your database.
what you are doing now is to add the text of your query in the total_sales column of your daily table.
You can refer to this answer to inspire yourself: Get sum of MySQL column in PHP
Also this page explains very well what you have to do, scroll down until you reach the example titled "Inserting the result of a query in another table with group by".

The code that worked was simple:
$result= mysqli_query($link, "SELECT SUM(sales) as valuesum FROM daily);
$row = mysqli_fetch_assoc($result);
$total_sales = $row['valuesum'];
I couldn't manage it to work because there was other errors which i found from phpfpm-error.log

Try this way:
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'"
$sql = "INSERT INTO `daily` SET `date` = CURRENT_TIMESTAMP, `sales` = ' ".$sales." ', `total_sales` = ($query)";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Related

Add Form Data and Get Data from Another Table to Form a New Record After Submit - Php MySQL

5 fields from Table 1 come from the Php Form. 5 fields are extracted from Table 2, Table 3, Table 4, and Table 5.
Is this doable from Php?
Tried both multiple INSERT SELECT and VIEWS; however, a novice compared to some.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("site", "user", "password", "database");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$new_record_id = trim($_GET["id"]);
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email, city, state) VALUES ('Peter', 'Parker', 'peterparker#mail.com', 'williamsburg', 'new york')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Attempt insert query1 execution
$sql1 = "INSERT INTO persons (SELECT cust_type, cust_revenues, cust_since FROM customer) VALUES ('Existing', '3029', '2016') WHERE id = $new_record_id";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Attempt insert query2 execution
$sql2 = "INSERT INTO persons (SELECT order_no, order_date FROM orders) VALUES ('293048', '11/26/2016') WHERE id = $new_record_id";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
When submitting the Form, a new record should get created with data in all 10 fields. Currently, not happening.
I think I will replace the code with PDO hardened PHP statements and MySQLi. As well since no error codes are given (it returns a clean page), I think the result set is too big. I replaced the query to only perform an INSERT from the Form. The other tables will be aggregated into Views.

MYSQL Update statement not working, no associated error

I've seen a few posts dealing with UPDATE statements in MySQL, but none of them seem to apply to my specific situation.
I have the following code:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
Essentially, I'm trying to check to see if an entry exists. If it exists, then update it. If the entry doesn't exist, then make it.
The INSERT statement executes perfectly. However, the UPDATE statement does nothing. There is no error message, and no changes made in my table.
Any ideas?
Thanks!
As Forbs stated, your UPDATE statement will not result in any changes since you are filtering based on "current_timestamp", which will be whatever time the query executes. What you need to do instead is pass an existing timestamp into your code so that it updates whatever existing record already has that as its iso_date.
See the example below for how you can change your code.
//this is whatever your time is that you are looking for a record for
$isoDateDT = '2018-08-01 08:15:00';//human readable datetime
$isoDateTS = strtotime($isoDateDT);//unix timestamp
$result = "SELECT * FROM open_lab_report WHERE iso_date = $isoDateTS";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES ($isoDateTS, '$lab_monitor', 1)";
} else {
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = $isoDateTS";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
You have to correct your if statement checking.
In your Case you can count number of entries with same timestamp as current timestamp.
and then
if count<1 then you can UPDATE ,otherwise INSERT.
EXAMPLE:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
$row=mysqli_num_rows(mysqli_query($link, $result))
if($row<1){
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}

PHP ~ Column count doesn't match value count at row 1

Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();

MySql transaction works only in console

When i paste this into MySql console
START TRANSACTION;
INSERT INTO `orders` (customer_id) VALUES ('2');
SET #lastid=LAST_INSERT_ID();
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'3','2','4','4','2');
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'1','3','5','4','2');
COMMIT;
it works fine, when i try to do the same via php
$sql = "START TRANSACTION;";
$sql .="INSERT INTO `orders` (customer_id) VALUES ('$customer_id_form');";
$sql .="SET #lastid=LAST_INSERT_ID();";
foreach ($product_id_form as $key => $product){
$sql .= "INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES
(#lastid,'$product','$quantity_form[$key]',
'$price_form[$key]','$amount_form[$key]','$customer_id_form');";
}
$sql .= "COMMIT;";
//$sql = "INSERT INTO products (`product_name`,`curent_price`,`product_quota`) VALUES ('$productname_form','$productprice_form','$productquote_form')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
header("Location: order.php");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
mysqli_close($con);
it does not work error shown is
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'INSERT INTO orders (customer_id) VALUES ('2');SET
#lastid=LAST_INSERT_ID();INS' at line 1
Perform the queries one at a time; do not try to send them all at once to the server. The START...COMMIT will determine the transactional semantics.
I think you need multi_query, to execute multiple queries

SQL Slow connection, insert respect select

I have a table with a user id and a date, several users connect at the same time and only one user a day can do insert in the database.
I have a slow connection to the server and what it takes to do the select of the last entry, whether it has been today or not, since it can not be a primary key because the date can vary, sometimes it makes double registrations for the same day.
How can I do this so that this does not happen and I only insure an insert a day?
Thank you
Code:
<?php
$sql = "SELECT MAX(timestamp_pole) as last_pole FROM pole WHERE id_group = ". $id_grup;
$resultado = $mysqli->query($sql);
$resultado = $resultado->fetch_assoc();
$las_00 = date('Y-m-d');
$las_00 = strtotime($las_00);
if ($resultado['last_pole'] >= $las_00){
} else {
$sql = "INSERT INTO pole (timestamp_pole, id_user, id_group) VALUES (". $timestamp .",". $user['id'] .",". $id_group .")";
$mysqli->query($sql);
//return addslashes($sql);
if (isset($user['username']))
return "#". $user['username'] ." pole!";
else
return $user['name'] ." pole!";
}
?>
you can create unique index using (date, id_group) as key, by that way you can make sure that there isn't any duplicated date in same group. Also remember to implement try/ catch as running insert query.

Categories