SQL Can't Delete from Table - php

I have a PHP and I want to do 2 inserts and 1 delete, but I can only make an insert. If the array containt the last parameter == "historico" should delete from instant_table all register with same serial_num and inserte the array intro the instant_table and insert in historical_table("SensorData"). Ifnot (the array don't hace the parameter "historico"), should de delete from instant_table all register with same serial_num and only inserte the array intro the instant_table.
My code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$serial_numb = test_input($_POST["serial_numb"]);
$DHTtempC = test_input($_POST["DHTtempC"]);
$DHThumid = test_input($_POST["DHThumid"]);
$CCS811_CO2 = test_input($_POST["CCS811_CO2"]);
$CCS811_tVOC = test_input($_POST["CCS811_tVOC"]);
$PM25 = test_input($_POST["PM25"]);
$PM10 = test_input($_POST["PM10"]);
$reading_date = date("Y-m-d");
$update_status = test_input($_POST["update_status"]);
$tipo_tabla = test_input($_POST["tipo_tabla"]);
// Create connection
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if ($tipo_tabla == "historico"){
$sql = "INSERT INTO SensorData (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
}
$sql = "DELETE FROM instant_data WHERE (serial_numb = '" . $serial_numb . "')";
$sql = "INSERT INTO instant_data (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->close();
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Tu sum up, If the array contains the parameter, INSERTE(TABLE1) + DELETE with same serial_num(TABLE2) + INSERTE(TABLE2). If not DELETE with same serial_num(TABLE2) + INSERTE(TABLE2).
EDIT: Now this code only make the second INSERT

It seems like you are overwriting the content of $sql without executing the queries in between. You have to either:
execute each query before redefining $sql
use $sql .= (instead of $sql =) to concatenate the next query. If you do this, you have to terminate your sql query with an ; before concatenating the next query.
Are you using this code just for an small personal project or are you going to publish this in any way? In case of the later one:
please read into PHP SQL best practices. With your current approach you are vulnerable to SQL injections and your code is kinda difficult to read.

Related

how to check duplicate records in mysql database

$queryb = "SELECT product, imei, country, warranty, config from PRODUCT WHERE product_slno = '$mnserialno' ";
$resultb = mysql_query($queryb, $gndbconn) ;
if(mysql_num_rows($resultb) > 0)
{
$queryc = "UPDATE PRODUCT SET product='$desc', product_slno='$mnserialno',imei='$imei',country='$country',warranty='$warranty',config='$config' WHERE product_slno = '.$mnserialno.' ";
$resutc = mysql_query($queryc, $gndbconn) ;
}
else{
$querya = "INSERT INTO PRODUCT SET product='$desc', product_slno='$mnserialno',imei='$imei',country='$country',warranty='$warranty',config='$config'";
$resulta = mysql_query($querya, $gndbconn) ;
}
I want to check the serial number if that serial number already exist in database so records get update, otherwise it get insert into the database.
but the code inserting the records only, no updation, what is the fault i am not getting,
how to prevent the duplicate entry?
INSERT INTO PRODUCT SET
(`product`, `product_slno`, `imei`, `country`, `warranty`, `config`)
VALUES
('" . $desc . "', '" . $mnserialno . "', '" . $imei . "', '" . $country . "', '" . $warranty . "', '" . $config . "')
ON DUPLICATE KEY UPDATE
product='" . $desc . "',
product_slno='" . $mnserialno . "',
imei='" . $imei . "',
country='" . $country . "',
warranty='" . $warranty . "',
config='" . $config . "'";

I want to show an error if duplicates are there in database using php and mysql

I'm trying to show an error while entering duplicates using php and mysql, but i'm not getting how to complete, please give an solution........
this is my code:
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
}
You have to create unique key in productcost table , using unique fields like (product, productCategory, model). Now execute insert query, if there is a recode in the table return error . now you can handle error and give message.
try{
mysql_query("INSERT INTO productcost (product_key_id,product, productCategory,model,purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES
('" . $_POST["created_product_id"] . "','" . $_POST["product"] . "','".$_POST["productCategory"] . "','" . $_POST["model"] . "','".$_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','".$_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','".$_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
return TRUE;
}
catch(Exception $e){
return FALSE;
}
or you can check is there a recode in table before insert
select count(*) as cc from doc_upload where product_key_id = $_POST["created_product_id"];
To show an error message while entering duplicates:
// First check there are same data available or not using a query by counting the row
$sqlCheck = "SELECT COUNT(`id`) WHERE product = '" . $_POST["product"] . "' AND productCategory = '" . $_POST["productCategory"] . "' AND model = '" . $_POST["model"] . "'"; // You have to add mroe thing in where clause
$CheckQuery = mysql_query($sqlCheck);
// if there is no duplicate data
//
if ($CheckQuery > 0) {
# code...
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
} else {
$message = "Data is Duplicated";
}
Note : I'm Giving you an Example . this is how you have to check
duplicate data

Php Mysqli not updating data in database

Here is my code, it works and no errors pop up and the correct data for the variables are there.
When it's all done it shows Done for the last echo.
However, when I go into heidisql to view the database table, nothing has changed, even when I run the query in heidisql, still same results.
// Make connection to database
$connection = mysqli_connect($host,$user,$pass,$dbnm);
// Make query
$myQuery = "
UPDATE Ekhaya_Inventory SET
ekhaya_inventory_stock_item = '" . $stockItemPost . "',
ekhaya_inventory_stock_left = '" . $stockLeftPost . "',
ekhaya_inventory_stock_out = '" . $stockOutPost . "',
ekhaya_inventory_stock_minimum = '" . $stockMinimumPost . "',
ekhaya_inventory_stock_price_per_item = '" . $stockPricePIPost . "',
ekhaya_inventory_value_of_stock_left = '" . $stockValueOfStockLeftPost . "'
WHERE
ekhaya_inventory_stock_code = '" . $stockCodePost . "'
AND
ekhaya_inventory_stock_code = '" . $stockLocationPost . "'
";
mysqli_query($connection,$myQuery)or die("Error: ".mysqli_error($connection));
mysqli_close($connection)or die("Error: ".mysqli_error($connection));
echo "<br>Done";
WHERE
ekhaya_inventory_stock_code = '" . $stockCodePost . "'
AND
ekhaya_inventory_stock_code = '" . $stockLocationPost . "'
it is wrong because one field can`t contain two different values in the same time

escape null values(Nestoria UK)

I am able to retrieve data from a website(Nestoria) and store into my PostGIS database. However not every individual result that is returned have latitude and longitude values and as such they are not stored into the database. I tried using (pg_escape_string) so that it can return null values as double quotes(") but it didn't work. The field type of my lat and long columns in the database is "double precision".
This is a sample output of the error: ("Warning: pg_query() [function.pg-query]: Query failed: ERROR: invalid input syntax for type double precision: "" LINE 1: ...droom garden flat set in a period building with...', '', '') ^ in C:\XAMMP...\database.php on line 12")
Please see the code below for retrieving the data:
<?php
$url = ("http://api.nestoria.co.uk/api?action=search_listings&centre_point=51.5424,-0.1734,2km&listing_type=rent&property_type=all&price_min=min&price_max=max&bedroom_min=0&bedroom_max=0&number_of_results=50&has_photo=1&page=4");
$xml = simplexml_load_file($url);
foreach ($xml->response->listings as $entry) {
echo $entry->attributes()->title;
echo $entry->attributes()->bathroom_number;
echo $entry->attributes()->bedroom_number;
echo $entry->attributes()->datasource_name;
echo $entry->attributes()->guid;
echo $entry->attributes()->img_url;
echo $entry->attributes()->keywords;
echo $entry->attributes()->lister_name;
echo $entry->attributes()->listing_type;
echo $entry->attributes()->price;
echo $entry->attributes()->price_type;
echo $entry->attributes()->property_type;
echo $entry->attributes()->summary;
echo $entry->attributes()->latitude;
echo $entry->attributes()->longitude;
// Process XML file
}
?>
Find below the code to store values into database:
<?php
require 'nestoriauk.php';
// Opens a connection to a PostgresSQL server
$connection = pg_connect("dbname=postgis user=postgres password=xxxx");
// Execute query
foreach ($xml->response->listings as $entry) {
$query = "INSERT INTO nestoriaphp(title, bathroom, bedroom, datasource, guid, image, keywords, lister, listype, price, pricetype, property_type, summary, latitude, longitude) VALUES ('" . pg_escape_string($entry->attributes()->title) . "', '" . pg_escape_string($entry->attributes()->bathroom_number) . "', '" . pg_escape_string($entry->attributes()->bedroom_number) . "', '" . pg_escape_string($entry->attributes()->datasource_name) . "', '" . pg_escape_string($entry->attributes()->guid) ."', '" . pg_escape_string($entry->attributes()->img_url) . "', '" . pg_escape_string($entry->attributes()->keywords) . "', '" . pg_escape_string($entry->attributes()->lister_name) . "', '" . pg_escape_string($entry->attributes()->listing_type) . "', '" . pg_escape_string($entry->attributes()->price) . "', '" . pg_escape_string($entry->attributes()->price_type) . "', '" . pg_escape_string($entry->attributes()->property_type) ."', '" . pg_escape_string($entry->attributes()->summary) . "', '" . pg_escape_string($entry->attributes()->latitude) . "', '" . pg_escape_string($entry->attributes()->longitude) . "')";
$result = pg_query($query);
printf ("These values are inserted into the database - %s %s %s", $entry->attributes()->title, $entry->attributes()->bathroom_number, $entry->attributes()->bedroom_number, $entry->attributes()->datasource_name, $entry->attributes()->guid, $entry->attributes()->img_url, $entry->attributes()->keywords, $entry->attributes()->lister_name, $entry->attributes()->listing_type, $entry->attributes()->price, $entry->attributes()->price_type, $entry->attributes()->property_type, $entry->attributes()->summary, $entry->attributes()->latitude, $entry->attributes()->longitude);
}
pg_close();
?>
Yemi
If a POI has no lat-lon, which value it has? empty string?
assuming that an empty string is returned when there is no lat-lon.
$lon = "NULL";
if($entry->attributes()->longitude != "")
$lon = "'".$entry->attributes()->longitude."'";
$lat = "NULL";
if($entry->attributes()->latitude != "")
$lat = "'".$entry->attributes()->latitude."'";
so query looks like this:
$query = "INSERT INTO nestoriaphp(title, bathroom, bedroom, datasource, guid, image, keywords, lister, listype, price, pricetype, property_type, summary, latitude, longitude) VALUES ('" . pg_escape_string($entry->attributes()->title) . "', '" . pg_escape_string($entry->attributes()->bathroom_number) . "', '" . pg_escape_string($entry->attributes()->bedroom_number) . "', '" . pg_escape_string($entry->attributes()->datasource_name) . "', '" . pg_escape_string($entry->attributes()->guid) ."', '" . pg_escape_string($entry->attributes()->img_url) . "', '" . pg_escape_string($entry->attributes()->keywords) . "', '" . pg_escape_string($entry->attributes()->lister_name) . "', '" . pg_escape_string($entry->attributes()->listing_type) . "', '" . pg_escape_string($entry->attributes()->price) . "', '" . pg_escape_string($entry->attributes()->price_type) . "', '" . pg_escape_string($entry->attributes()->property_type) ."', '" . pg_escape_string($entry->attributes()->summary) . "', " . $lat . ", " . $lon . ")";
Note that the NULL value has no '' in sql.

PHP MySQLi INSERT not working, no errors

Different from this question, but similar in that I don't get an error when adding information to my database.
$sql = "INSERT INTO 'nlcc_ver1'.'tUsers' ('userID', 'userName', 'userPassword', 'userHash',
'user_first_name', 'user_last_name', 'user_corps', 'is_admin', 'is_trg', 'is_sup', 'is_co')
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" . $f_name . "', '" .
$l_name . "', '" . $corps . "', '" . $admin . "', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli_query($mysqli, $sql);
echo "Query run. Inserted UserID " . mysqli_insert_id($mysqli) . "<br />";
Line breaks inserted to avoid sideways scrolling... It says on the web page that mysqli_insert_id($mysqli) is 0, and nothing is added to the table on my database. I do not see an error connecting to the database appearing, and MySQL is running on my server, and phpinfo() shows both the MySQL and MySQLI extension loaded. This is just a development machine, so don't worry about the security (i.e. no password). I have tried googling the problem, but am not finding too much. I don't know about object oriented PHP programming with ->, I am used to using _. Is this method still supported?
You've mixed procedural and object-oriented MySQLi styles. This has led to you trying to use the functions like mysqli_query($mysqli) instead of the member functions like $mysqli->query(). Your $mysqli is an object, not a resource handle.
And, you're not performing any error checking on your query. If you were, you'd see that you have mistakenly used single quotes to delimit table and field names, not backticks.
$sql = "INSERT INTO `nlcc_ver1`.`tUsers`
(`userID`, `userName`, `userPassword`, `userHash`,
`user_first_name`, `user_last_name`, `user_corps`,
`is_admin`, `is_trg`, `is_sup`, `is_co`)
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" .
$f_name . "', '" . $l_name . "', '" . $corps . "', '" . $admin .
"', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if (!$result) {
printf("%s\n", $mysqli->error);
exit();
}
echo "Query run. Inserted UserID " . $mysqli->insert_id . "<br />";
I strongly suggest using the manual as your reference. It's quite clear on how to use these functions when you're using either procedural or object-oriented style MySQLi.
$mysqli_query($mysqli, $sql);
should be
mysqli_query($mysqli, $sql);
OR
$mysqli->query($sql);
AND later on
$mysqli->insert_id();
Look at this:
'nlcc_ver1'.'tUsers'
You have to use backticks here as quote character:
`nlcc_ver1`.`tUsers`
But however(assuming that the $ in $mysqli_query is just a typo): You will not get errors for the query , unless you use mysqli_error() right after executing the query.
SET AutoCommit = 1 before inserting
$mysqli->query('SET AUTOCOMMIT = 1');

Categories