PHP MySQL Update query array(0) { } - php

Can anybody help me to understand why my query update dosen't update my data in my database.
This my code php :
<?php
$code = $_GET['code'];
$n1= $_GET['n1'];
$n2= $_GET['n2'];
$n3 = $_GET['n3'];
try {
$connexion= new PDO('mysql:host=localhost;dbname=data','mydata','password');
$sql_update = "UPDATE data.check SET numb_1='".$n1."',numb_2='".$n2."','numb_3'='".n3."' WHERE 'code_product' =".$code;
$query = $connexion-> prepare($sql_update);
$query -> execute();
$data_update= $query -> fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "<br>" . $e->getMessage();
}
Thanks for any help.

1) Change
$sql_update = "UPDATE data.check SET numb_1='" . $n1 . "',numb_2='" . $n2 . "','numb_3'='" . n3 . "' WHERE 'code_product' =" . $code;
To
$sql_update = "UPDATE data.check SET numb_1='" . $n1 . "',numb_2='" . $n2 . "','numb_3'='" . $n3 . "' WHERE `code_product` =" . $code;
=> In n3 you forgot to add $. And, replace single quotes with backtick to enclose column name.
Updated Code
<?php
$code = $_GET['code'];
$n1 = $_GET['n1'];
$n2 = $_GET['n2'];
$n3 = $_GET['n3'];
try {
$connexion = new PDO('mysql:host=localhost;dbname=data', 'mydata', 'password');
$sql_update = $connexion->prepare("UPDATE `data`.`check` SET numb_1 = :numb_1 , numb_2 = :numb_2, numb_3 = :numb_3 WHERE `code_product` = :code_product");
$sql_update->execute(array(':numb_1' => $n1,':numb_2'=>$n2, ':numb_3'=>$n3,':code_product'=>$code));
$stmt = $connexion->prepare("SELECT * FROM `data`.`check` WHERE code_product=:code_product");
$stmt->execute(array(':code_product'=>$code));
$data_update= $stmt -> fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "<br>" . $e->getMessage();
}
?>

After your update execution you need to query again for fetching result like,
$sql_update = "UPDATE data.check SET numb_1='".$n1."',numb_2='".$n2."','numb_3'='".$n3."' WHERE 'code_product' =".$code;
$query = $connexion-> prepare($sql_update);
$query -> execute();
$query = $dbh->prepare("SELECT * FROM data.check");
$query->execute();
$data_update= $query -> fetchAll(PDO::FETCH_ASSOC);// now it will get records

Related

Cannot update the row in mysql via php

I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;

PDO Statements aren't being submitted to database

I'm fairly new to using PDO, and I'm attempting to migrate some of my websites from mysql_* to it.
I have formed the following:
if ($userData) {
$query = "SELECT * FROM table WHERE user_id = " . $db->quote($userData['id']);
$result = $db->query($query);
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = " . $db->quote($userData['id']) . "' AND `id` != '" . $row['id'];
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
if (!$row) {
$sql = "INSERT INTO tokens SET `user_id` = " . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute();
} else {
$sql = "UPDATE tokens SET `access_token` = " . $db->quote($token) . "' WHERE `id` = " . $row['id'] . "";
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
}
$userData is a Facebook API variable.
The snippet above looks fine to me, but when I run through it on a live website, the information isn't added to the database.
How would I fix this? Any assistance would be greatly appreciated.
You're missing a single quote
$sql = "INSERT INTO tokens SET `user_id` = <<HERE>>" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
should be:
$sql = "INSERT INTO tokens SET `user_id` = '" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
And on the update statement in the same place.
Ok I am going to tell you one thing, please use placeholders. I have also been through the same problem which you are in right now. mysql_ functions are deprecated and hence developers have to use PDO or mysqli_ functions.
Please check the code and see if it works
<?php
if($userData) {
$query = "SELECT * FROM table WHERE user_id = :user_id";
$result = $db->prepare($query);
$result->execute(array(':user_id' => $userData['id']));
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = :user_id AND `id` != :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':id' => $row['id']));
}
}
if(!$row) {
$sql = "INSERT INTO tokens SET `user_id` = :user_id, `name` = :name,`access_token` = :access_token ,`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':name' => $userData['name'], ':access_token' => $token));
} else {
$sql = "UPDATE tokens SET `access_token` = :access_token WHERE `id` = :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':access_token' => $token, ':id' => $row['id']));
}
}
}
?>

SQL Connection creates excessive concurrent HTTP connections to the host

I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.

Check if condition and then update Magento

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

MAGENTO: How can I update category_ids from file?

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.

Categories