insert into select on duplicate key update - php

I'm try to create a database where i save users search.
I want insert term when this term don't exist and adding +1 when exist but all other specific field on database are the same.
Example:
user1 search playstation with price 1 = insert into database
user2 search playstation with price 1 = +1 on the same row generated by user1
user3 search playstation with price 1 and condition new = insert into database a new record
I have write this but don't work:
<?php
$link = mysqli_connect("localhost", "root", "root", "keyword");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// attempt insert query execution
$sql = "INSERT INTO keyword (id, search, category, mn, mx, site, itmcond, free, sortorder, type, payp) VALUES ('".$_GET["id"]."', '".$_GET["search"]."', '".$_GET["category"]."', '".$_GET["mn"]."', '".$_GET["mx"]."', '".$_GET["site"]."', '".$_GET["itmcond"]."', '".$_GET["free"]."', '".$_GET["sortorder"]."', '".$_GET["type"]."', '".$_GET["payp"]."')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Anyone can help me to understand where use INSERT INTO for add search to database, SELECT for find the term previously insered and ON DUPLICATE KEY UPDATE for adding +1 for the same search.
Thanks!

$sql = "INSERT INTO keyword (id, search, category, mn, mx, site, itmcond, free, sortorder, type, payp) VALUES ('".$_GET["id"]."', '".$_GET["search"]."', '".$_GET["category"]."', '".$_GET["mn"]."', '".$_GET["mx"]."', '".$_GET["site"]."', '".$_GET["itmcond"]."', '".$_GET["free"]."', '".$_GET["sortorder"]."', '".$_GET["type"]."', '".$_GET["payp"]."')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
//add this
die();
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>

Related

column doesnt match when its empty

How should i solve this? there is not a row 1 and i cant insert or update data. Unique keys are indeed ip and uid in my table.
My code is as follows:
//Retrive listeners per reload
echo 'Data Höganäs <br>';
$sc="http://USER:PWD#SUB.SERVER.se:10000/admin.cgi?sid=1&mode=viewxml&page=3";
$xml2 = simplexml_load_file($sc);
foreach ($xml2->LISTENERS->LISTENER as $listener2) {
// Create connection
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " insert INTO hoganaskey
(ip, uid, tid, starttid, date)
VALUES
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
on duplicate key
update tid='$listener2->CONNECTTIME' ";
//$sql = "INSERT INTO hoganaskey (ip, uid, tid, ua, starttid, date) VALUES('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT' '$starttid', '$date') ON DUPLICATE KEY UPDATE tid='$listener2->CONNECTTIME' ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} //End foreach SHOUcast listener
Im returning this error in insert "Column count doesn't match value count at row 1".
In your insert query, you listed only 5 field names:
(ip, uid, tid, starttid, date)
but you are passing 6 values not 5:
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')

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.

How to add a number from an HTML form to a number already in Database?

So I have an HTML form, which is sending data to a database via an "input.php" file which I have connected to my database.
What I wanted to accomplish, is that the data being sent to the database from the HTML form is all numbers. I wanted to know how I can code the input.php file so that when new numbers get submitted from the HTML form, and get sent to a value which already has a number, to add the two up.
For example, Person A fills out a number in the form on day one, per say 5. The next day, he submits the exact same field with the number 3. In the database, instead of overriding the first value, I want to add it up. So on day 1, the database should say "5", but on day 2, it should say "8".
Here is my bare-bones "input.php" file which I will use. The names for the fields will change in my finalized code.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('$first_name', '$last_name', '$email')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Any help would be appreciated. I thought maybe I could use some javascript validation, however that would be for validating the field, and not adding...so...
Thanks!
Let's say the column name is counts which needs to be summed, and column index id, you could use ON DUPLICATE KEY UPDATE to update based on id if it's already exist, and insert a new row if it's not exist:
UPDATE: You don't need the id field in this situation, as you can automate it using an AUTO_INCREMENT.
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email, counts) VALUES
('$first_name', '$last_name', '$email', '$counts')
ON DUPLICATE KEY UPDATE counts = counts + $counts";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
Two things you need to do. First, verify if the record exists or not. Second, If exists update the record by adding the form input to the column . If not exists then insert new record with form input. To update you can write query like
UPDATE TABLE_NAME
SET column_to_update = column_to_update+form_input_number
WHERE email=<email_address> ;
(assuming email is the primary key or replace email with any primary key field name)

how to update value of the specific column from a table after deleting data

guy's i need help for this problem guy's
i have a table with 4 column. no, name, address, phone. the case is after i do deleting one data i must decrease column no with how many data i delete.
last time i make a program using vb.net i can do this. i use this code i can do it well
Dim ab As Integer
ab = lvrak.Items(i).SubItems(4).Text
Dim stok As New SqlClient.SqlCommand("Update tbl_barangluar set jumlah_barang=jumlah_barang - '" & ab & "' where kode_barang='" & _
lvrak.Items(i).SubItems(0).Text & "'")
stok.Connection = koneksi
stok.ExecuteNonQuery()
but now i need to do that in php function. and im really dont know how to do it.
i try just do ex. update temp5 set no='$no' - 1 and it not going well. someone please help me
This my Trial PHP
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
// Attempt insert query execution
$sql = "DELETE FROM temp5 WHERE no='$no'";
if(mysqli_query($db, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
// Close connection
mysqli_close($db);
?>
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
// Attempt insert query execution
$sql = "alter table temp5 auto_increment = 1";
if(mysqli_query($db, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
// Close connection
mysqli_close($db);
?>
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
$min = 1;
// Attempt insert query execution
$sql = "UPDATE temp5 SET no=no -1 where no";
if(mysqli_query($db, $sql)){
echo "Records inserted successfully.";
} else{
echo "Records inserted failed ";
}
mysqli_close($db);
?>
I will add a picture before and after delete function has do.
the problem is there. i have try to do limiting them but is give more eror.
in the 1st picture is contain all the data before delete. and i will do delete the data with no 4. and the result is in picture 2. that result is wrong.. the result must be 1,2,3,4
You need to update the count after delete success
UPDATE temp5 SET no=no -1
PHP :
<?php include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
$sql = "DELETE FROM temp5 WHERE no='$no'";
if(mysqli_query($db, $sql)){
$sql1 = "UPDATE temp5 SET no=no -1";
mysqli_query($db, $sql1);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}

Insert values to mysql from select query

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);
}

Categories