This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if value exist in mysql
I have a small script to upload data to mysql database from a csv file and I want to check the list of values that are inside of the csv file.
This is the CSV File to check if values from csv exist in db:
code,alert_quantity
12345,10
This my proeject PHP File:
<?php
$link_id = mysql_connect("localhost", "root", "")
or die("Could not connect.");
if(!mysql_select_db("database",$link_id))
die("database was not selected.");
function _checkIfCodeExists($code){
$sql = "SELECT COUNT(*) AS count_no FROM products WHERE code = ?";
$count = $sql;
if($count > 0){
return true;
}else{
return false;
}
}
function _updateData($line_of_data){
$code = $line_of_data[0];
$newAlert = $line_of_data[1];
$sql = "UPDATE ";
}
$file_handle = fopen("file.csv", "r");
while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE) {
$query = mysql_query("SELECT * FROM products WHERE code ='$line_of_data[0]'") or die(mysql_error());
$message = '';
$count = 1;
if(_checkIfCodeExists($line_of_data[0])){
try{
_updateData($_data);
$message .= $count . '> Success:: Product with code (' . $line_of_data[1] . ') Exist (' . $line_of_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While updating alert (' . $line_of_data[1] . ') of code (' . $line_of_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product code (' . $line_of_data[0] . ') Doesnt exist<br />';
}
$count++;
echo $message;
}
?>
I don't know what you're doing here, but it isn't going to work:
$sql = "SELECT COUNT(*) AS count_no FROM products WHERE code = ?";
$count = $sql;
if($count > 0){
return true;
This is equivalent to:
if ("SELECT COUNT(*)..." > 0)
That will never be true.
Related
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
I have this script, it works, i can make an update for the quantities . The only problem i have is the fact that the csv is too big...
I tried to set the memory limit but when i'm loading the page the server says "The waiting time is exceeded. The server at www.auto-univers.fr takes too long to respond. "
What can i do ?
is that it is possible to update the line from 1 to 1000 for example? I do like his two update in 2 different pages, line 1 to 1000 and 1000 to the end line.
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
set_time_limit(0);
ini_set('memory_limit','2048M');
function _getConnection($type = 'core_read'){
return Mage::getSingleton('core/resource')->getConnection($type);
}
function _getTableName($tableName){
return Mage::getSingleton('core/resource')->getTableName($tableName);
}
function _getAttributeId($attribute_code = 'price'){
$connection = _getConnection('core_read');
$sql = "SELECT attribute_id
FROM " . _getTableName('eav_attribute') . "
WHERE
entity_type_id = ?
AND attribute_code = ?";
$entity_type_id = _getEntityTypeId();
return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getEntityTypeId($entity_type_code = 'catalog_product'){
$connection = _getConnection('core_read');
$sql = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
return $connection->fetchOne($sql, array($entity_type_code));
}
function _checkIfSkuExists($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
function _getIdFromSku($sku){
$connection = _getConnection('core_read');
$sql = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
return $connection->fetchOne($sql, array($sku));
}
function _updateStocks($data){
$connection = _getConnection('core_write');
$sku = $data[0];
$newQty = $data[1];
$productId = _getIdFromSku($sku);
$attributeId = _getAttributeId();
$sql = "UPDATE " . _getTableName('cataloginventory_stock_item') . " csi,
" . _getTableName('cataloginventory_stock_status') . " css
SET
csi.qty = ?,
csi.is_in_stock = ?,
css.qty = ?,
css.stock_status = ?
WHERE
csi.product_id = ?
AND csi.product_id = css.product_id";
$isInStock = $newQty > 0 ? 1 : 0;
$stockStatus = $newQty > 0 ? 1 : 0;
$connection->query($sql, array($newQty, $isInStock, $newQty, $stockStatus, $productId));
}
$csv = new Varien_File_Csv();
$csv->setDelimiter(';');
$data = $csv->getData('supply.csv'); //path to csv
array_shift($data);
$message = '';
$count = 1;
foreach($data as $_data){
if(_checkIfSkuExists($_data[0])){
try{
_updateStocks($_data);
$message .= $count . '> Success:: Quantité (' . $_data[1] . ') de la référence (' . $_data[0] . ') a été mis à jour. <br />';
}catch(Exception $e){
$message .= $count .'> Erreur:: Lors de l\'update de la quantité (' . $_data[1] . ') de la référence (' . $_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Erreur:: Produit avec la référence (' . $_data[0] . ') n\'existe pas.<br />';
}
$count++;
}
echo $message;
I'm skeptical this script would exceed max execution time, but to answer your question, you could always keep track of how many lines have been processed and then stop execution after 10000. You could also use an offset and limit passed in from the $_GET parameters to make it more controllable and dynamic.
you can either split the csv or use array_slice method to split the results from csv.
http://www.php.net/manual/en/function.array-slice.php
I am trying to check if files exist in a folder and then if they don't, I want to update my sql database. As of now I am looping through an array of id's that should have a number corresponding to the file number in the database. This means that I am querying the sql database multiple times vs one time. Is it possible and more efficient to make just one query? Here is what my code looks like:
$photo_status = "SELECT id FROM photo_set_table WHERE Photo_added = 1";
$photo_added = mysql_query($photo_status);
if (!$photo_added) {
die('Invalid query: ' . mysql_error());
}
$path = '/home/aXXXXXXX/public_html/';
$path .= '/images_android/images/';
$no_photo_array = array();
while($added = mysql_fetch_array($photo_added))
{
if(!file_exists($path.$added[0].'.jpg')){
array_push($no_photo_array, $added[0]);
}
}//while added
$count_changes = 0;
foreach ($no_photo_array as $value) {
$change_status = "UPDATE photo_set_table SET Photo_added = 0 WHERE id = $value";
$photo_added2 = mysql_query($change_status);
if (!$photo_added2) {
die('Invalid query: ' . mysql_error());
} else {
$count_changes++;
}
} //foreach ($no_photo_array....
echo "The number of affected lines is: ".$count_changes;
mysql_close($connection);
You could try this:
$count_changes = 0;
if (count($no_photo_array) > 0) {
$sInClause = implode(',', $no_photo_array);
$sSql = "UPDATE photo_set_table SET Photo_added = 0 WHERE id IN (" . $sInClause . ")";
$bStatus = mysql_query($sSql);
if ($bStatus) {
$count_changes = mysql_affected_rows();
} else {
die('Invalid query: ' . mysql_error());
}
} //foreach ($no_photo_array....
echo "The number of affected lines is: ".$count_changes;
need to update price list in magento if a condition is true, if it is false skip.
The issue is that don't know why the function _checkIfSkuInStock is returning 1 for all.
I set one product to be in stock and one to be out of stock.
Below is the code that is updating the price list if the sku exist, and i want to add also the the condition if product is in stock, else skip.
function _getConnection($type = 'core_read'){
return Mage::getSingleton('core/resource')->getConnection($type);
}
function _getTableName($tableName){
return Mage::getSingleton('core/resource')->getTableName($tableName);
}
function _getAttributeId($attribute_code = 'special_price'){
$connection = _getConnection('core_read');
$sql = "SELECT attribute_id
FROM " . _getTableName('eav_attribute') . "
WHERE
entity_type_id = ?
AND attribute_code = ?";
$entity_type_id = _getEntityTypeId();
return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getEntityTypeId($entity_type_code = 'catalog_product'){
$connection = _getConnection('core_read');
$sql = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
return $connection->fetchOne($sql, array($entity_type_code));
}
function _getIdFromSku($sku){
$connection = _getConnection('core_read');
$sql = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
return $connection->fetchOne($sql, array($sku));
}
function _checkIfSkuExists($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
function _checkIfSkuInStock($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('cataloginventory_stock_item') . " WHERE is_in_stock = 1";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
function _updatePrices($data){
$connection = _getConnection('core_write');
$sku = $data[0];
$newspecial_price = $data[1];
$productId = _getIdFromSku($sku);
$attributeId = _getAttributeId();
$sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
SET cped.value = ?
WHERE cped.attribute_id = ?
AND cped.entity_id = ?";
$connection->query($sql, array($newspecial_price, $attributeId, $productId));
}
$csv = new Varien_File_Csv();
$data = $csv->getData('special_price.csv'); //path to csv
array_shift($data);
$message = '';
$count = 1;
foreach($data as $_data){
if(_checkIfSkuExists($_data[0]) and _checkIfSkuInStock($_data[0]) == 0){
try{
_updatePrices($_data);
$message .= $count . '> Success:: (' . $_data[1] . ') product code (' . $_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While Upating Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product code (' . $_data[0] . ') not in database<br />';
}
$count++;
}
echo $message;
Any help is appreciated.
In this code :
function _checkIfSkuInStock($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('cataloginventory_stock_item') . " WHERE is_in_stock = 1";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
You try to populate with sku : $connection->fetchOne($sql, array($sku));
But you don't have any prepared field (?) in your request.
Add something like this :
"SELECT COUNT(*) AS count_no FROM " . _getTableName('cataloginventory_stock_item') . " WHERE is_in_stock = 1 AND product_id=?"
And then use
$connection->fetchOne($sql, array($this->_getIdFromSku($sku)));
It should work better ;)
I have csv file with following structure. I want to update product category path from this file. How I can do this.
sku,category_ids
0001,"1,2,3"
0002,"1,2,4"
I using flowing script to update prices
$mageFilename = '../app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
set_time_limit(0);
ini_set('memory_limit','1024M');
/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
return Mage::getSingleton('core/resource')->getConnection($type);
}
function _getTableName($tableName){
return Mage::getSingleton('core/resource')->getTableName($tableName);
}
function _getAttributeId($attribute_code = 'category_ids'){
$connection = _getConnection('core_read');
$sql = "SELECT attribute_id
FROM " . _getTableName('eav_attribute') . "
WHERE
entity_type_id = ?
AND attribute_code = ?";
$entity_type_id = _getEntityTypeId();
return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getEntityTypeId($entity_type_code = 'catalog_product'){
$connection = _getConnection('core_read');
$sql = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
return $connection->fetchOne($sql, array($entity_type_code));
}
function _getIdFromSku($sku){
$connection = _getConnection('core_read');
$sql = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
return $connection->fetchOne($sql, array($sku));
}
function _checkIfSkuExists($sku){
$connection = _getConnection('core_read');
$sql = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
$count = $connection->fetchOne($sql, array($sku));
if($count > 0){
return true;
}else{
return false;
}
}
function _updatePrices($data){
$connection = _getConnection('core_write');
$sku = $data[0];
$newPrice = $data[1];
$productId = _getIdFromSku($sku);
$attributeId = _getAttributeId();
$sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
SET cped.value = ?
WHERE cped.attribute_id = ?
AND cped.entity_id = ?";
$connection->query($sql, array($newPrice, $attributeId, $productId));
}
/***************** UTILITY FUNCTIONS ********************/
$csv = new Varien_File_Csv();
$data = $csv->getData('prices.csv'); //path to csv
array_shift($data);
$message = '';
$count = 1;
foreach($data as $_data){
if(_checkIfSkuExists($_data[0])){
try{
_updatePrices($_data);
$message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While Upating Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
}
$count++;
}
echo $message;
I don't know which table to be updated. What needs to change in this code to work update category_ids.
Unless you have a specific reason for using a custom script, you can always use the normal System -> Import/Export -> Dataflow: Profiles -> Import All Products using the file you described.
If you are truly looking for a script I can amend my answer for you.