PDO doesn't work when updating multiple rows with transactions - pdo

I'm gonna execute multiple rows of a table in same time with an instance of pdo.
I tried this :
try {
$pdo->beginTransaction();
$query = $pdo->prepare('UPDATE forum_config SET config_value = ? WHERE config_name = ?');
$query->execute(array('activate_avatar', $_POST['activate_avatar']));
$query->execute(array('activate_mp', $_POST['activate_mp']));
$query->execute(array('activate_sign', $_POST['activate_sign']));
$query->execute(array('allow_register', $_POST['allow_register']));
$query->execute(array('avatar_max_height', $_POST['avatar_max_height']));
$query->execute(array('avatar_max_size', $_POST['avatar_max_size']));
$query->execute(array('avatar_max_width', $_POST['avatar_max_width']));
$query->execute(array('cookies_expires', $_POST['cookies_expires']));
$query->execute(array('domain_name', $_POST['domain_name']));
$query->execute(array('forum_style', $_POST['forum_style']));
$query->execute(array('post_flood_time', $_POST['post_flood_time']));
$query->execute(array('post_max_size', $_POST['post_max_size']));
$query->execute(array('post_max_smilies', $_POST['post_max_smilies']));
$query->execute(array('session_time_out', $_POST['session_time_out']));
$query->execute(array('sign_max_size', $_POST['sign_max_size']));
$query->execute(array('site_closed_reason', $_POST['site_closed_reason']));
$query->execute(array('site_open', $_POST['site_open']));
$query->execute(array('topic_flood_time', $_POST['topic_flood_time']));
$query->execute(array('topic_max_size', $_POST['topic_max_size']));
$pdo->commit();
}
catch(Exception $e) {
$pdo->rollback();
die('Erreur : '.$e->getMessage());
}
unset($query);
But it doesn't do anything. What is the problem? Thanks for your help

Related

I am stuck, mysqli_query() expects at least 2 parameters

I have a problem with a code in php it shows me this as errors.
register
mysqli_query() expects at least 2 parameters, 1 given in
C:\xampp\htdocs\search_engine\insert.php on line 99
And this is the code :
<?php
$db = new PDO('mysql:host=localhost;dbname=srgn;charset=utf8mb4', 'root', '123456');
if(isset($_POST["submit"]))
{
$s_link = $_POST["s_link"];
$s_key = $_POST["s_key"];
$s_des = $_POST["s_des"];
{
$sql = "insert(site_link, site_key, site_des) values('$s_link', '$s_key', '$s_des')";
$rs = mysqli_query($sql);
if($rs)
{
echo "<script> alert('Site uploaded successfully') </script>";
}
else
{
echo "<script> alert('Uploading failed, please try agin.') </script>";
}
}
}
?>
Where is the error please, and how can I set it?
Pass on the connection link as the first parameter and the SQL query as the second parameter. This is required as you are doing procedural code. Refer to the link below for more details
http://php.net/manual/en/mysqli.query.php

PHP InstanceOf works locally but not on host server

I have an issue with PHP 7's instanceof statement that is only happening on certain conditions.
It seems that instanceof works locally on my dev machine (MAMP Pro running PHP 7.0.13) but not on my Hosted Server (HostEurope, PHP 7).
I have tried the following :
downgrading to PHP 5.6
using is_a instead
Using fully qualified name e.g. \Site\Ad
but they all exhibit the same behaviour.
I've tried Googling "PHP instanceof not working" and variations of it but I haven't found anything relevant.
I was wondering if anyone had experienced something similar or possible solutions to try?
The Code in question is:
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../site/AdMediumRectangle.php");
require_once(__DIR__."/../site/AdSnapBanner.php");
require_once(__DIR__."/../const/Const.php");
class AdFactory
{
/**
* Define(AD_BANNER, 0);
* Define(AD_RECTANGE, 1);
* Define(AD_SUPERBANNER, 2);
* Define(AD_SKYSCRAPER, 3);
**/
/**
* #param $object
* #return AdMediumRectangle|AdSnapBanner|string
*/
public static function CreateObject($object)
{
$ad = wire(pages)->get("/ads/")->children->getRandom();
if ($ad == null)
return new \Exception("No Random Ad found");
switch ($object) {
case AD_BANNER:
echo "AD_Banner Selected\r\n";
$adSnapBanner = new AdSnapBanner($ad);
return $adSnapBanner;
break;
case AD_RECTANGLE:
echo "AD Rectangle Created\r\n";
$adRectangle = new AdMediumRectangle($ad);
return $adRectangle;
break;
case AD_SUPERBANNER:
case AD_SKYSCRAPER:
default:
echo "AdFactory BlankObject created";
return "";
break;
}
}
public static function Markup($object)
{
$obj = AdFactory::CreateObject($object);
if (($obj instanceof AdSnapBanner) || ($obj instanceof AdMediumRectangle)) {
echo "InstanceOf worked";
return $obj->Markup();
}
else {
echo "return blankString";
return "";
}
}
}
Update : This is the code that calls the above AdFactory class
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../factory/AdFactory.php");
require_once (__DIR__."/../const/Const.php");
class AdInjector
{
public static function Inject($page, $ad_pos)
{
//Select an Ad from /Ads/ according to criteria
//$ads = wire(pages)->get("/ads/")->children;
$count = 1; //$ads->count();
if ($count > 0) {
$mod = $page->id % 3;
echo "mod=" . $mod . "\r\n";
if ($mod == $ad_pos) {
switch ($mod) {
case AD_POS_TITLE;
case AD_POS_BANNER:
//Pick an Snap Banner
echo "Banner Injected (banner):" . AD_BANNER . "\r\n";
return AdFactory::Markup(AD_BANNER);
break;
case AD_POS_SIBLINGS:
echo "Banner Injected (rect):" . AD_RECTANGLE . "\r\n";
//Pick an Ad Rectangle
return AdFactory::Markup(AD_RECTANGLE);
break;
default:
return "";
break;
}
} else
return "";
} else
return "";
}
}
instanceof is a language construct which is so essential to PHP that it is de facto impossible not to work properly.
The code you provided is not enough to tell where the issue might be happening.
Chances are, you have a folder not readable on your online server and simply get somewhere a null value instead of an expected object along your code. Ask yourself: "If it is not the object I expect, what else is it?"
Use var_dump() or printf() to investigate what your variables actually contain and you will find the error soon.
For your code, PHPUnit tests would be a benefit, or at least the use of assert() here and there in your code.
Turns out there was a bug in 1 of the API calls I was making to the Processwire CMS.
$ad = wire(pages)->get("/ads/")->children->getRandom();
And my local and server instance of Processwire was not the same version, which was news to me. I normally have it synchronised, including any modules I use.
I also suspect my null check is not correct PHP, to add to the problem.
It has to do with namespaces used in the code:
Locally (Code with no namespaces) I used this, working fine:
if ($xmlornot instanceof SimpleXMLElement) { }
But on the server (code with namespaces) only this worked:
if ($xmlornot instanceof \SimpleXMLElement) { }
See also this question/answer: instanceof operator returns false for true condition

CloudSQL persitent connections error

I'm using Google Cloud SQL 2nd generations instances and persistent connections using PHP PDO driver but, from time to time, and just in some App Engine instances, the pooled connections get corrupted and the connections begin to fail, sending an ugly message to the user.
I tried to solve this trying to make new connnections, even disabling persistency, but it didn't work:
for ($attempt = 1; !$this->link; $attempt++) {
try {
if ($attempt > $persistent / 2) {
unset($options[PDO::ATTR_PERSISTENT]);
}
$this->link = new PDO($dsn_string, $user, $pass, $options);
} catch (PDOException $err) {
if ($attempt <= $persistent) {
usleep($attempt * 100000);
} else {
throw new DB_Exception("Error connecting database (after $attempt attempts):\n" . $err->getMessage(), $err->getCode(), null, $err);
}
}
}

PDO LastInsertId returning nothing

For some reason I cannot get the LastInsertId from my PDO insert. I am receiving nothing back, if I place it inside the execute I get -1 because the insert query hasn't run. However when just after the execute to grab the last ID inserted nothing is returned.
php 5.1.6
PECL pdo = 0.1.0
I have looked at following questions and many other stack exchange questions.
lastInsertId does not work in Postgresql
PDO lastInsertId() returns 0
PDO lastInsertId issues, php
However the difference is nothing is returned compared to 0. No errors are recorded either. See the code below.
Connection
try {
$conn = new PDO("pgsql:host=localhost port= dbname=", "", "");
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
insert / return the last id
$stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id, username, additionalvolunteers) VALUES(?,?,?)");
$stmt->bindParam(1,$site_id);
$stmt->bindParam(2,$username1);
$stmt->bindParam(3,$additionalvolunteers);
$site_id = $_POST['site_id'];
$username1 = $user->name;
$additionalvolunteers = $_POST['additionalvolunteers'];
$stmt ->execute();
$newsheetID = $conn->lastInsertId('sheet_id');
echo $newsheetID . "last id";
You should be using
$newsheetID = $conn->lastInsertId('sheet_id_**seq**');
Just add _seq after id.
Assumming sheet_id type is SERIAL you can use LASTVAL()
TRY (Not tested as I dont have postgresql)
$newsheetID = $conn->query("SELECT LASTVAL()");
echo $newsheetID . "last id";
I use postgresql in C# with the "RETURNING rowkey" and its has always worked for me.
I also use pdo/php in a lot of applications.
However i dont have a postgres database open to the server right now for testing.
This could should work but it is not tested.
$site_id = $_POST['site_id'];
$username1 = $user->name;
$additionalvolunteers = $_POST['additionalvolunteers'];
$stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id, username, additionalvolunteers) VALUES(:site_id, :username1, :additionalvolunteers) RETURNING row_id");
$success = $stmt->execute([
'site_id' => $site_id,
'username1' => $username1,
'additionalvolunteers' => $additionalvolunteers
]);
// unsure about this
$newsheetID = $stmt->fetchColumn();
echo $newsheetID . " last id";

How to do mysql_fetch_array in Magento

I want to create a drop down option using Magento module that populate the data from the database I created.
Previously, I have this code in My IndexController.php which is work. This is the first code.
public function dropdownAction() {
if (file_exists('./app/etc/local.xml')) {
$xml = simplexml_load_file('./app/etc/local.xml');
$tblprefix = $xml->global->resources->db->table_prefix;
$dbhost = $xml->global->resources->default_setup->connection->host;
$dbuser = $xml->global->resources->default_setup->connection->username;
$dbpass = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname;
}
else {
exit('Failed to open ./app/etc/local.xml');
}
$link = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname) or die("Unable to select database");
$tblname = $tblprefix.'my_db_table';
$result = mysql_query("SELECT dropdowndata FROM ".$tblname."");
echo '<select>';
while ($ary = mysql_fetch_array($result)){
echo "<option>" . $ary['dropdowndata '] . "</option>";
}
echo "</select>";
mysql_close($link);
}
But I think the code above is not the Magento way. Do you agree?
Now, I want to populate the data with this code in IndexController.php. This is the second code.
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<select>";
echo "<option>" .$optionData."</option>";
echo "</select>";
}
}
Using the code above, the data was populated but one data with one drop down option. So there are so many drop down options appear on the browser, each drop down option will contain only one data.
I think I am missing the while ($ary = mysql_fetch_array($result)). But I confuse how to include that code?
So, my question is how to do mysql_fetch_array in Magento? Or can somebody please explain how to make the second code above work like the first code.
getData() function returns an array of the whole data, and of course need move 'select' nodes out of the foreach
echo "<select>";
foreach($options as $option){
$optionData = $option->getData();
echo "<option>" .$optionData['somekey'] ."</option>";
}
echo "</select>";
But I think would be better use the magento magic functions, for example if you have 'entity_id' column in DB you can get value using $option->getEntityId(), etc...
And why do you have select inside of foreach? I think something like this will solve your problem:
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
echo "<select>";
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<option>" .$optionData."</option>";
}
echo "</select>";
}