PHP / MySQL : Insert if doesnt exist else update [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
create a mysql record if it doesnt exist, else update it
I have created a bit of PHP that gets data from a CSV and updates a Database Table to match the CSV's data.
My next task is, To check if the record exists, based on the unique column (sku). If it does exist update the database table dependant on the change.
Otherwise if that SKU column doesnt match do the INSERT.
The code I've got at the moment runs, However the issue I have is that if a new item is created it seems to run the update through the already existing records.
My code can be found on Pastebin
Or also here...
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect' . mysql_error());
}
mysql_select_db("db_lemonstand", $con);
class csvIterator extends LimitIterator
{
public function __construct($path)
{
$csv = new SplFileObject($path);
$csv->setFlags(SplFileObject::READ_CSV);
parent::__construct($csv, 1);
}
}
foreach (new csvIterator('data/catalogue.csv') as $entry) {
$name = $entry[23];
/* Replace Strings To Make URL Name */
$search_array = array(" ", "/", "+");
$replace_array = array("-");
$url_name = strtolower($name);
$url_name = str_replace($search_array, $replace_array, $url_name);
$long_desc = $entry[9];
$short_desc = $entry[23];
$manufacturer = $entry[11];
$price = $entry[15];
$sku = $entry[2];
$weight = $entry[29];
$width = $entry[30];
$height = $entry[5];
$enabled = '1';
$created_at = date('Y-m-d H:i:s');
$product_type_id = '1';
$tax_class_id = '1';
echo '<pre>';
print_r($entry);
echo '</pre>';
// Check see if products' SLU already exists or not
$product_exists = "SELECT sku FROM shop_products WHERE sku = '$sku'";
$result = mysql_query($product_exists, $con);
$exists = mysql_num_rows($result);
if($exists == 0 )
{
$insert = "INSERT INTO shop_products (name, description, short_description, url_name, price, sku, weight, width, height, enabled, created_at, tax_class_id, product_type_id) VALUES ('$name', '$long_desc', '$short_desc', '$url_name', '$price', '$sku', '$weight', '$width', '$height', '$enabled', '$created_at', '$tax_class_id', '$product_type_id')";
$insert_data = mysql_query($insert, $con);
}
else
{
$update = "UPDATE shop_products SET name = '$name', description = '$long_desc', short_description = '$short_desc', url_name = '$url_name', price = '$price', sku = '$sku', weight = '$weight', height = '$height', enabled = '$enabled', created_at = '$created_at', tax_class_id = '$tax_class_id', product_type_id = '$product_type_id'";
$update_data = mysql_query($update, $con);
if (!mysql_query($update,$con))
{
die('Error: ' . mysql_error());
}
}
}

You can use
INSERT INTO mytable on DUPLICATE KEY UPDATE...

You must set unique key for your table (one or more fields) and than you can use this ability.
In my example I have unique key (template, date)
$sql = 'INSERT INTO myTable
(`template`,`date`,`count`) VALUES
("' . $template . '","' . $curDate . '", 1)
ON DUPLICATE KEY UPDATE count = count + 1';

Store store you fields in a var as $fields or anything else that you want and execute this query for that you need a single field as reference that's why i included $Id
INSERT INTO table_name SET id = '$Id', $fields ON DUPLICATE KEY UPDATE $fields

Related

INSERT only first row and ignore New entries

I made a form for pharma products where user select the manufacturers name and write the details of the project. Everything is up and running fine except only this issue. Its been hours and i cant figure it out.
The problem is Its only selects the first row and ignore new entries. What i want is it will select every row or every new entry and insert into second database here the code is working with no errors but update only the first row.
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($perm) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
$rows = mysqli_fetch_array($result34);
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
With prepared statement:
$sql2 = "INSERT INTO final1 (Name, Category) VALUES (?, ?);";
$stmt1 = mysqli_stmt_init($dbc);
if (!mysqli_stmt_prepare($stmt1, $sql2)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt1, "ss", $namey, $category);
mysqli_stmt_execute($stmt1);
}
you need while loop
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($result34) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
while($rows = mysqli_fetch_array($result34) ){
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
}
?>

Mysql Column count doesn't match value count at row 1 error while inserting data

I'm having This error while trying to save data to mysql and i cant see any error here
$cons_no = $_POST['cons_no'];
$ship_name = $_POST['ship_name'];
$ship_location = $_POST['ship_location'];
$phone = $_POST['phone'];
$s_add = $_POST['s_add'];
$r_name = $_POST['r_name'];
$r_phone = $_POST['r_phone'];
$r_add = $_POST['r_add'];
$type = $_POST['type'];
$weight = $_POST['weight'];
$invoice_no = $_POST['invoice_no'];
$qty = $_POST['qty'];
$book_mode = $_POST['book_mode'];
$freight = $_POST['freight'];
$mode = $_POST['mode'];
$pick_date = $_POST['pick_date'];
$pick_time = $_POST['pick_time'];
$status = $_POST['status'];
$comments = $_POST['comments'];
$r_country = $_POST['r_country'];
The only this not in the code is the cid which is auto increment
$sql = "INSERT INTO tbl_courier (cons_no, ship_name, ship_location, phone, s_add, r_name, r_phone, r_add, type, weight, invoice_no, qty, book_mode, freight, mode, pick_date, pick_time, status, comments, r_country)
VALUES('$cons_no', '$ship_name', '$ship_location', '$phone', '$s_add', '$r_name', '$r_phone', '$r_add', '$type', '$weight', $invoice_no, '$qty', '$freight', '$mode', '$pick_date', '$pick_time', '$status', '$comments', '$r_country')";
I don't know your builded SQL string, but I can assume you have empty values.. to prevent that you can add additional check before assign a value.
$status = isset($_POST['status'])?$_POST['status']:0; // default 0 if don't exists
Edit:
I see your query, the answer is: the field book_mode is missing in values sentence

Add Xml data to database

I have made this code to put in a database some webradio data from an xml witch is working, the problem is if the mp3 file as no album it messes up the data entry, can someone point a way to if $pieces[1] exists run the code and add the album if not don't do anything, and add the others in the right place.
$title = $xml->SONGTITLE;
$pieces = explode("-", $title);
$pieces[0] = trim($pieces[0]);
$pieces[1] = trim($pieces[1]);
$pieces[2] = trim($pieces[2]);
// performing sql query
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)";
$result = mysqli_query($con, $sql);
Maybe just add : if ($pieces[1]!="") ?
$title = $xml->SONGTITLE;
$pieces = explode("-", $title);
$pieces[0] = trim($pieces[0]);
$pieces[1] = trim($pieces[1]);
$pieces[2] = trim($pieces[2]);
if ($pieces[1]!="")
{
// performing sql query
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)";
$result = mysqli_query($con, $sql);
}
Yes that quite easy you just need to check if the value has been set.
if(isset($value_to_check))
{
//true - your item has a value.
}
else
{
//do somthing else.
}

Check to Insert or Update table

See the code below, it check if the data exist in the table, if not exist then insert it or else update the table.
As you can see it look a bit messy - is there anyway to improve the code logic or something smaller? I have a few tables that need doing same thing.
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
Note: I am aware about PDO but I don't have time to replace it on existing system.
Use mysql's REPLACE INTO or INSERT... ON DUPLICATE KEY UPDATE. For example:
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
mysql_query($SQLInsert);
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
}
}
}
Also you can use INSERT IGNORE construction

mysql syntax problem

I'm trying to display info from a mysql row on this page. I'm using $_GET, because the id is included in the link to the page: www.example.com/page.php?id=1 but it returns this error:
Error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '1'' at line 1
Does anyone know how to fix this?
code below:
<?php
$username="xxx";
$password="xxx";
$database="xxx";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
include 'library/config.php';
include 'library/opendb.php';
if(isset($_GET['id']))
{
$query = "SELECT id, title, content, contactname, contactemail, contactnumber ".
"FROM vacancies".
"WHERE id = '{$_GET['id']}'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($id, $title, $content, $contactname, $contactemail, $contactnumber) = mysql_fetch_array($result, MYSQL_NUM);
$content = htmlspecialchars($content);
}
if(isset($_POST['update']))
{
$id = $_POST['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$contactname = $_POST['contactname'];
$contactemail = $_POST['contactemail'];
$contactnumber = $_POST['contactnumber'];
if(!get_magic_quotes_gpc())
{
$title = addslashes($title);
$content = addslashes($content);
$contactname = addslashes($contactname);
$contactemail = addslashes($contactemail);
$contactnumber = addslashes($contactnumber);
}
// update the article in the database
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber'".
"WHERE id = '$id'";
mysql_query($query) or die('Error : ' . mysql_error());
// then remove the cached file
$cacheDir = dirname(__FILE__) . '/cache/';
$cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
#unlink($cacheFile);
// and remove the index.html too because the file list
// is changed
#unlink($cacheDir . 'index.html');
echo "<b>Job Entry: '$title' updated</b>";
// now we will display $title & content
// so strip out any slashes
$title = stripslashes($title);
$content = stripslashes($content);
$contactname = stripslashes($contactname);
$contactemail = stripslashes($contactemail);
$contactnumber = stripslashes($contactnumber);
}
include 'library/closedb.php';
?>
Check out http://us2.php.net/manual/en/function.mysql-query.php
The problem is that you are using too many single quotes here:
"WHERE id = '{$_GET['id']}'";
and your query is not acting as expected. use mysql_real_escape_string() instead.
Try this:
$query = "SELECT id, title, content, contactname, contactemail, contactnumber ".
"FROM vacancies ".
"WHERE id = '".$_GET['id']."'";
I always try to leave the variables out of my strings, just add them in with periods, I find it eliminates a lot of confusion.
One problem:
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber'".
"WHERE id = '$id'";
results in no space between the last column and the WHERE clause. Change it to:
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber' ".
"WHERE id = '$id'";
or my preferred format:
$query = <<<END
UPDATE vacancies
SET title = '$title',
content = '$content',
contactname = '$contactname',
contactemail = '$contactemail',
contactnumber = '$contactnumber'
WHERE id = '$id'
END;
Note: You should really escape the fields using mysql_real_escape_string().
Remove the quotes around
{$_GET['id']}
and
$id
in all your queries.
Your id is of type integer I assume, which can't take a quoted version or it tries to match the integer key to the string "1"
--
Change this line
$result = mysql_query($query) or die('Error : ' . mysql_error());
to
$result = mysql_query($query) or die('Error : ' . mysql_error() . "\n\n" . $query);
Then you can see exactly what query is going into the DB. Which you can then post here for us to see.
Also please post a
describe <tablename>;

Categories