Modify insert into to update - php

I want to modify my code so instead of just inserting a new row in the MySQL table, it can check to see if there is one with the same item number, and update it.
php code
<?php
$con=mysqli_connect("localhost","root","root","inventory");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

You can use ON DUPLICATE KEY UPDATE syntax,
$sql = "
INSERT INTO `current stock` (ItemNumber, Stock)
VALUES ('$_POST[ItemNumber]', '$_POST[Stock]' )
ON DUPLICATE KEY UPDATE
Stock = '$_POST[Stock]'
";
ItemNumber should be primary/unique key in this case

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')

Conditional insert or update in mysql

I have a table with input of type time and I want to check first if there is a row with the current date and the id of employee, if it was I update the value of the input if not I insert a new row. This is what I have tried but it always inserts a new row even if the condition exists:
<?php
$E1=$_POST['E1'];
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$sql1="SELECT * FROM retards WHERE Date ='Curdate()' AND
IdEmpl='".$_POST["IdEmp"]."' ;";
$result1=mysqli_query($connect,$sql1);
if(!$result1){
die('ERREUR SQL ! <br>'.$sql.'<br>'.mysqli_error());}
if($dt=mysqli_fetch_array($result1,MYSQLI_ASSOC)){
$sql="update retards set E1='$E1' where IdEmpl='".$_POST["IdEmp"]."' AND
Date=CURDATE();";
}
else{
$sql="insert into retards(IdEmpl,Date,E1) values
('".$_POST["IdEmp"]."',CURDATE(),'$E1'); ";
}
$result = mysqli_query($connect, $sql);
if (!$result)
{
echo("Error description: " . mysqli_error($connect));
}
else {
$message ="Effectué avec succès!";
echo "<script type='text/javascript'>alert('$message'); </script>";
}
mysqli_close($connect);
?>
This is known as an upsert which can be done in mysql using the insert ... on duplicate key update syntax.
insert into t (a, b, c) values (?, ?, ?)
on duplicate key update b = ?
Your table should have an appropriate unique index or primary key defined on the column(s) of interest.

Copy value to another table

I have a problem with my code. I have a table called "users" with an "id" field.I want to copy the id value to another table called "aircondition" . This is the code that inserts values into the aircondition table .The problem is that when I use this code I get 0 in the new id field instead of the user.id
<?php
$con=mysqli_connect("localhost","george","george123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
VALUES ('SELECT id
FROM users', '$acname', '$btu', '$space', '$energyclass')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
Use this query
INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users

Multiple insert issue

When I use this code, I get one record for each id stored in the users table. Instead, I want to be able to insert only 1 record each time, the one that matches the logged users id.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
You must have a where clause in your select statement
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users WHERE usernamecolumn= currentusername ;

How to get the sum of time from database in PHP?

I wanted to get the sum of this column in my database and display it in home page. Here is the screen shot
http://bit.ly/1fJ7Cey
I use this code to save data on my Database
$timeanddate=$_POST['timeanddate'];
$time=$_POST['tst'];
$name=$_POST['name'];
$number=$_POST['number'];
$disposition=$_POST['disposition'];
$remarks=$_POST['remarks'];
$times=$_POST['timetoday'];
$dates=$_POST['datetoday'];
if(isset($_POST['submit']))
{
session_start();
$con=mysqli_connect("localhost","root","","hsncs_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO hsncs_tbl (id, name, number, call_disposition, remarks, time, date, time_duration, hsncs_user)
VALUES
('', '$_POST[name]', '$_POST[number]', '$_POST[disposition]', '$_POST[remarks]', '$_POST[timetoday]', '$_POST[datetoday]', '$_POST[tst]', '$_SESSION[fname]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
If this column time is of data type "time" in mysql then your query would be
SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time_duration` ) ) ) AS timeSum FROM hsncs_tbl;

Categories