PHP command line persistent connections - php

I have a PHP script which works perfectly via Apache called through a browser, but the same code called on command line seems to drop the database connection after every call.
So for instance in an included file I have:
$pdo = new PDO('mysql:host=' . HOST . ';dbname=' . DB, USER, PASS, array(PDO::ATTR_PERSISTENT => true));
Then in my script I have:
$stmt = $pdo->prepare('SELECT intGroupID FROM tblquestiongroups WHERE dtDeleted IS NOT NULL ORDER BY RAND()');
$stmt->execute();
$something = $stmt->fetch(PDO::FETCH_ASSOC);
Which works fine, however directly afterwards I have:
$stmt = $pdo->prepare('SELECT intSurveyID FROM tblquestiongroups WHERE tblquestiongroups.intGroupID = :intQuestionId');
$stmt->bindValue(':intQuestionId', $intQuestionId);
$stmt->execute();
Which doesn't and returns:
Call to member function bindValue() on a non-object
Now if I add a new connection, i.e. copy and paste the one in the include file above the second call it all works fine again, i.e.:
$pdo = new PDO('mysql:host=' . HOST . ';dbname=' . DB, USER, PASS, array(PDO::ATTR_PERSISTENT => true));
$stmt = $pdo->prepare('SELECT intSurveyID FROM tblquestiongroups WHERE tblquestiongroups.intGroupID = :intQuestionId');
$stmt->bindValue(':intQuestionId', $intQuestionId);
$stmt->execute();
My first question is why won't PHP keep the connection open for the period of the script?
So onto my second question. As a test I went through and added the connection before all of the calls to database via PDO. Within this script I actually connect to two different servers and as such I have another connection defined which looks like this:
$pdoLocal = new PDO('mysql:host=' . HOST_LOCAL . ';dbname=' . DB_LOCAL, USER_LOCAL, PASS_LOCAL, array(PDO::ATTR_PERSISTENT => true));
So of course to try and get the thing working I have added this line above any calls to the local database. However with this code:
$pdoLocal = new PDO('mysql:host=' . HOST_LOCAL . ';dbname=' . DB_LOCAL, USER_LOCAL, PASS_LOCAL, array(PDO::ATTR_PERSISTENT => true));
$pdoLocal->beginTransaction();
$stmtInsert = $pdoLocal->prepare('INSERT INTO tblresponses_string (strResponses, intSurveyID) VALUES (:strResponses, :intSurveyID)');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$stmtInsert->bindValue(':strResponses', $row['strResponses']);
$stmtInsert->bindValue(':intSurveyID', $surveyID);
$stmtInsert->execute();
}
$pdoLocal->commit();
I get the same error on the first bind.
I guess this is the same problem in that the first statement to get executed is beginTransaction and the PDO connection closes afterwards.
As mentioned this all works fine through Apache.
All help gratefully received.

Your speculations are wrong.
If PHP were indeed dropping a connection, you'd had an error not on bindValue call but on the line where the very PDO connection is used, so, the error would be
Call to member function prepare() on a non-object
So, the problem is not with connection but with query. Set PDO in error mode:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
then see the error message and then either fix it or ask another question regarding this particular error.

Related

Simple PDO write not working

I'm trying to get a simple PDO insert to work. I have successfully created a tabled named mydb10 using PDO, and the next part I want to do is insert data into that table. Running the script does not return any errors (PDO error mode exception is enabled), but the table still contains null values.
I'm using a local server to run the PHP file, and am connecting to an Amazon RDS database. Currently all inbound traffic through SSH, HTTP, HTTPS, and MYSQL is allowed through the database's security group
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$username,$password);
$statement = $link->prepare("INSERT INTO mydb10 (selectedMain, selectedSide)
VALUES(:selectedMain, :selectedSide)");
$statement->execute(array(
"selectedMain" => "test",
"selectedSide" => "test2"
));
This might be silly, but I've been stuck for a while now and any help is appreciated. If you'd like any more information, let me know. I'm trying to utilize PHP in my app, but can't even get this simple test to work, so it's a bit discouraging.
EDIT # 1
This snippet is part of a larger file. I am able to successfully
connect to the database with my credentials and create new tables on the server. I do have PDO error reporting enabled in exception mode, and it has helped me work past syntax errors, but I am no longer getting any errors when I run the code. There are also no errors on the MYSQL server log.
I can provide any additional information that may be useful in debugging if desired.
First you need to properly set connection to MySQL database. You can write this code to sql.php:
<?php
$ServerName = "******";
$Username = "******";
$Password = "******";
$DataBase = "******";
try {
$CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
$CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Now, when you properly set connection, you need to execute sql, but before this you need to include sql.php:
try {
$SQL = 'INSERT INTO MyDB10 (SelectedMain, SelectedSide) VALUES(:SelectedMain, :SelectedSide)'; // Write SQL Query to variable
$SQL = $CONN->prepare($SQL); // Prepare SQL Query
$SQL->execute(array('SelectedMain' => 'Test', 'SelectedSide' => 'Test2')); // Execute data to Insert in MySQL Databse
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
When you finish all queries you must close connection with:
$CONN = null;

Run SQL script via PHP

I've created a backup.sql script to restore a MySql database. I've checked the script with PHPMyAdmin import and everything works fine (the database has been restored successfully). Now I would like to run it via PHP. I've found this question and I have:
1) created a PHP file into htdocs folder with the following content
$site_path= realpath(dirname(__FILE__)).'/';
$command = 'mysql'
. ' --host=' . 'localhost'
. ' --user=' . 'myuser'
. ' --password=' . 'mypass'
. ' --database=' . 'dbname'
. ' --execute="SOURCE ' . $site_path;
$output = shell_exec($command . 'backup.sql"');
echo "<pre>".$output."</pre>";
2) placed the backup.sql script into htdocs folder
But when I run the script, nothing happens on the database and nothing is displayed regarding shell_exec results. I'm running PHP and MySql under Apache on a windows machine. The command variable has the following value:
mysql --host=localhost --user=myuser --password=mypass--database=dbname --execute="SOURCE C:\Programmi\Apache Software Foundation\Apache2.2\htdocs/
What am I missing?
$mysql_host = "localhost";
$mysql_database = "db";
$mysql_user = "user";
$mysql_password = "password";
# MySQL with PDO_MYSQL
$db = new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
$query = file_get_contents("shop.sql");
$stmt = $db->prepare($query);
if ($stmt->execute())
echo "Success";
else
echo "Fail";
If you have the whole code in your sql file 100% correct and nothing to change on it, then try this, use PDO for better security in your code.
You can overcome this by using a MYSQL DBMS tool as Workbench where you can connect to the remote/local server and run the .sql file without the use of PHP.
PHP is meant to be used for applying business queries that reflect certain business functionality and not basically made for server actions or other tool jobs like DBMS tools..
If you really need to do this you can check this tutorial that reads the sql file and explode the queries into an Array using the ; character that shall delimit each query.
It then loops through each query in the array using foreach and executes the query on its own.
One thing I notice is that, the operation may take longer or if another operation is needed afterwards, especially during development to test that the file has been executed, the execute method will no to terminated.
I simple solution is to execute the query, then get the prepared query and run method rowCount,with this then we can safely test whether or not the execution has terminated.
So just use $count = $stmt->rowCount(); and not only $stmt->execute();
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$query = file_get_contents(__DIR__ . "/test.sql");
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->closeCursor();// Safely consuming the SQL operation till end
$count = $stmt->rowCount(); // Check if not pending transaction
if ($count) {
foreach($db->query('SELECT * from person') as $row) {
print_r($row);
}
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit;
}

I Can't Reach A DB Using PDO

I'm following a tutorial that is teaching PDO but I'm stuck at a very early point.
Referring to the code below I have diagnosed the problem down to the DB selected.
When I run print_r($query); there is no output and initallally I thought the problem was that the script wasn't connecting to the MySql server at all but then I learned if I change anything in host, user or pass I get an error message, but no matter what I change related to the database nothing happens and no error messages are displayed.
<?php
error_reporting(E_ALL);
$config['db'] = array(
'host' => 'xxxx',
'user' => 'xxxx',
'pass' => 'xxxx',
'database' => 'xxxx'
);
$db = new PDO('mysql:host=' . $config['db']['host'] . ';database=' . $config['db']['database'],$config['db']['user'], $config['db']['pass']);
$query = $db->query("SELECT `subscribers`.`first_name` FROM `subscribers`");
print_r($query);
echo 'Anything';
?>
If anyone could show me what Im doing wrong I'd be most appreciative and I thank you in advance.
BTW, I am SURE that SELECT subscribers.first_name FROM subscribers is correct as this works when I insert it into the mysql tab within php MyAdmin
I believe the DSN parameter for database name is called dbname, not database.
Try this:
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['database'],$config['db']['user'], $config['db']['pass']);
After creating a connection with database you need to create a statement, set query, bind values(optional), execute the query and fetch the result. In your case:
$db = new PDO('mysql:host=' . $config['db']['host'] . ';database=' . $config['db'] ['database'],$config['db']['user'], $config['db']['pass']);
$query = $db->prepare("SELECT `subscribers`.`first_name` FROM `subscribers`");
$query->execute();
$result = $query->fetchAll();
var_dump($result);

PHP PDO - can connect but query not working

I want to wean myself from the teat of the old mysql extension and am just doing a test PDO connection and simple query on a table in a database. I seem to be able to connect, ('connection successful' echoes out) but that's where the good times end. I have spent way too much time now just trying to get started with PDO.
<?php
$host = 'localhost';
$port = '3306';
$username = 'user';
$password = 'blabla';
$database = 'workslist';
try {
$db = new PDO("mysql:host=$host; port = $port; dbname = $database", $username, $password);
echo 'connection successful<br />';
$query = 'SELECT * FROM main';
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
$statement->closeCursor();
foreach($results as $r){
echo $r['work'] . '<br />';
}
} catch (PDOException $e) {
echo 'Error!: ' . $e->getMessage() . '<br />';
die();
}
?>
Is there anything wrong with the above?
The database name is 'workslist', the table name is 'main', and 'work' is one of the columns in that table. The PHP version I'm using is 5.3.4, and am using wamp on win7. I ran phpinfo() and under the PDO heading, the PDO drivers mysql, sqlite are enabled. To be sure the database and table actually exist I've tried it with MySQL and can return rows with the old mysql_fetch_array() method. I've checked the php.ini file to make sure the "extension=php_pdo..." lines are all uncommented.
cheers
This should work.
Please double-check that you actually have a table named "main" in that database.
Note that this error will not be discovered by PDO until you execute() the query, and if there is a problem with your query the default behavior is to return an empty result, not throw an exception.
To make PDO noisier, add the PDO::ERRMODE_EXCEPTION option when constructing PDO:
$db = new PDO("mysql:host=$host;port=$port;dbname=$database", $username, $password,
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
Now check if you see the following:
Error!: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'workslist.main' doesn't exist
The particular problem is that spaces aren't allowed in the DSN string. With the spaces, the "dbname" directive isn't processed, so there's no default database. Besides removing the spaces, explicitly specifying the database in the statement can help prevent this sort of problem:
SELECT `work` FROM `workslist`.`main`
That way, should there not be a default database for some reason, the query will still succeed.
PDO won't throw an error unless you configure it to:
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

How to execute mysql script with variables using PHP::PDO?

I am unable to execut long script the pdo throws an exception:
SQLSTATE[HY000]: General error
If I submit script which does not contain variables it runs w/o problem.
The same script runs on phpmyadmin interface.
Here is my code snippet:
try {
$dsn = "mysql:host=" . DB_SERVER . ";dbname=" . DB_DEFAULT;
$db = new PDO($dsn, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $db->query($query);
if (!$q) {
echo $db->errorInfo();
} else {
$rows = $q->fetchAll(PDO::FETCH_ASSOC);
}
} catch (PDOException $e) {
var_dump($e);
}
Here is some test which does not execute by PDO:
SET #ra_LMC:=80.9;
SELECT #ra_LMC;
How I should execut with pdo the multi line scripts?
Thanks
Arman.
PDO does not allow the execution of multiple statements in one query() request.
But your #ra_LMC variable should be visible in the current connection, so you can put your second line (SELECT) into a new query() call.
To read a whole script, you have to parse the file and run each statement with a call to query().
PDO can only execute one statement at a time. You can ether run the SET and SELECT as 2 separate statements. Or you can set the variable using FROM.
SELECT #ra_LMC FROM (SELECT #ra_LMC:=80.9) q

Categories