Run SQL script via PHP - 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;
}

Related

Laravel 8 connect to MSSQL 2000 issue

OS: CentOS 7
DB: MSSQL 2000
Larvel: 8
PHP: 7.4.26
My project need to use Laravel 8 eloquent to connect to MSSQL 2000, MSSQL 2000 is too old to be connected by modern PHP SQL server driver, people suggest using ODBC + FreeTDS, so I take this article as a reference, I successfully connect to the SQL server by native PHP code via PDO, just like the example in that article.
<?php
$host = '{IP}';
$port = '1433';
$dbname = '{DATABASE}';
$username = '{USERNAME}';
$password = '{PASSWORD}';
try {
$dsn ='odbc:Driver=FreeTDS;Server=' . $host . ';Port=' . $port . ';Database=' . $dbname . ';UID=' . $username . ';PWD=' . $password . ';clientcharset=UTF-8';
$dbConn = new PDO($dsn);
$stmt = $dbConn->query("SELECT TOP 2 t.*
FROM {DATABASE}.dbo.{TABLE} t
WHERE CREATOR = '{SOMEONE}'
ORDER BY CREATE_DATE DESC");
$row = $stmt->fetchAll();
echo '<pre>';
var_dump($row);
echo '</pre>';
} catch (PDOException $e) {
echo $e->getMessage();
}
Then I go to packagist to search ODBC package for Laravel and try:
https://packagist.org/packages/yoramdelangen/laravel-pdo-odbc
https://packagist.org/packages/cooperl/laravel-db2
https://packagist.org/packages/abram/laravel-odbc
https://packagist.org/packages/dbt/odbc-driver
Laravel was able to connect to the SQL server, but I got some error messages if has SQL condition:
Table::where("CREATE_DATE", $this->date)
->orWhere("MODI_DATE", $this->date)
->get();
SQLSTATE[42000]: Syntax error or access violation: 306 [FreeTDS][SQL Server]The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. (SQLExecute[306] at /builddir/build/BUILD/php-7.4.26/ext/pdo_odbc/odbc_stmt.c:259) (SQL: select * from "{TABLE}" where "{TABLE}"."CREATE_DATE" = 20060419 or "{TABLE}"."MODIFY_DATE" = 20060419)
I think it's not caused by the packages, but I try the SQL statement in native PHP with the same driver works perfectly, have no idea.

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

Issues with PHP connection script to MSSQL database

Good morning,
I am quite new to php and I am trying to create a connection to a MSSQL server, I've been able to do it through MYSQL php connection but what I thought would be a simply change to MSSQL is proving to be much harder than expected.
The below code is basically what I am using after much googleing and search in this website this is what i've come up with:
<?php
$Server = "127.0.0.1";
$User = "BOB123";
$Pass = "BOBPASS";
$DB = "BOBDB";
//connection to the database
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbconn)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT CustomerName from tblCustomer ";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<br>" . $row["name"];
}
//close the connection
mssql_close($dbconn);
?>
As you can see the above script is very basic and there are very similar ones knocking around on the web could anyone help in connecting to the server this script doesn't seem to want to connect. I've changed the log on details as you'd probably know.
Thanks
Kris
You have a typo on:
$dbconn = mssql_connect($Server, $User, $Pass);
Should be:
$dbconn = mysql_connect($Server, $User, $Pass);
You're typing mysql wrong on each mysql_ function you create, change all mssql_ to mysql_
Note:
You shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi.
#Daniel Gelling Doesn't look like a typo, looks like he is trying to connect to Microsoft SQL Server using mssql. You are correct about the API being outdated however.

PHP command line persistent connections

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.

How to use SQLite3 in a portable fashion with PHP(5.4.x)

I am attracted by the grand claims of SQLite, too. However, just that like many other software, I have run into obsolete and not so easy to follow documentation and blogs by kind developers. Without more griping, here are the questions and details of the environment:
I have a web host provider running PHP 5.2.17, with installed SQLite version 2.8.17. phpinfo() output says (under pdo_sqlite section) that SQLite version is 3.3.7. At home, I have Apache server running PHP 5.4.10. phpinfo() works fine at both sites. The home laptop says (under sqlite3) the version is 3.7.7.1.
About the problem, I want to create a db with a few tables, and ftp it (the data file) back and forth between the home computer and the remote host. I am trying to create a PHP script to
Create table if not exists legs ...
Delete existing rows
Insert a few new rows
Read the table and print it out as Html table
Somehow I made up this file dbc1.php which runs fine on the remote server. A similar file dbc2.php fails on the "if not exists" clause, then on other statements, and cannot even read the database file if it was created by dbc1.php. The error message is:
file is encrypted or is not a database
If I move the file, dbc2.php will create it, but cannot fetch the inserted rows. The localhost version complains that
"Call to undefined function sqlite_libversion() in C:\Web\php\dbcheck.php on line 14"
In my php.ini file, I have both extensions "php_pdo_sqlite.dll" and "php_sqlite3.dll" uncommented, and checked that both the dll files exist in the "ext" folder. What else do I need to do? The questions:
Is the style in dbc1.php preferred over dbc2.php? Why or why not?
Are the SQLite database files truly portable as claimed?
May I have a pointer to PHP5-SQLite3 tutorial?
Why do I get different version numbers from phpinfo() and sqlite_libversion()?
Thank you in advance for the responses. The 3 PHP files are below, although I hope to use 1 single file to perform the operations.
<html>
Testing SQLite with PHP
';
echo "SQLite version: " . sqlite_libversion() . '';
$db = new PDO('sqlite:dbname.db'); echo "[SQLite] DB opened<br/>";
$db -> exec ($qc0); echo "[SQLite] table created<br/>";
$db -> exec ($qr1); echo "[SQLite] Rows deleted<br/>";
$db -> exec ($qi1); $db -> exec ($qi2);
$db -> exec ($qi3); $db -> exec ($qi4); echo "[SQLite] Rows inserted<br/>";
try {
$rowsOfTable = $db -> query ($qr5);
print "\t<table border='0' cellspacing='4' cellpadding='4'\n" .
"\t\t\tstyle='padding-top:20px;'>\n";
print "\t\t<tr><td>Creation</td><td>Legs</td></tr>\n";
foreach ($rowsOfTable as $row) {
echo "\t\t<tr>\n" .
"\t\t\t<td>" . $row['name'] . "</td>\n" .
"\t\t\t<td align='right'>" . $row['count'] . "</td>\n" .
"\t\t</tr>\n";
}
print "\t</table>\n";
} catch (PDOException $ex) {
die ($ex->getMessage());
}
?>
Here is the file on the same Unix server that does not work:
<html>
Testing SQLite with PHP
\n";
echo "SQLite version: " . sqlite_libversion() . "\n";
try {
$db = new SQLiteDatabase('./dbname.db', 0644, $error);
echo "SQLite DB opened<br/>\n";
$db -> queryExec ($qc0, $error); echo "[SQLite] table created<br/>\n";
$db -> queryExec ($qr1, $error); echo "[SQLite] Rows deleted<br/>";
$db -> queryExec ($qi1, $error);
$db -> queryExec ($qi2, $error);
$db -> queryExec ($qi3, $error);
$db -> queryExec ($qi4, $error); echo "[SQLite] Rows inserted<br/><br/>";
if ($tableFromDB = sqlite_query ($db, $qr5, SQLITE_BOTH, $error)) {
print "\t<table border='2' cellpadding='4'>\n";
while ($row = $tableFromDB -> fetch()) {
print "\t\t<tr>\n" .
"\t\t\t<td>" . $row['name'] .
"</td><td>" . $row['count'] . "</td>\n\t</tr>\n";
}
print "\t</table>\n";
} else {
echo "Cannot query DB table: $error\n";
}} catch (Exception $ex) {
die ($error);
}
?>
And finally, the code I am trying to run on the laptop:
<html>
Testing SQLite with PHP
phpinfo();
echo "PHP version: " . phpversion() . '';
echo "SQLite version: " . sqlite_libversion() . '';
$db = new PDO('sqlite:dbname.db'); echo "[SQLite] DB opened<br/>";
$db -> exec ($qc0); echo "[SQLite] table created<br/>";
$db -> exec ($qr1); echo "[SQLite] Rows deleted<br/>";
$db -> exec ($qi1); $db -> exec ($qi2);
$db -> exec ($qi3); $db -> exec ($qi4); echo "[SQLite] Rows inserted<br/>";
try {
$rowsOfTable = $db -> query ($qr5);
print "\t<table align='center' border='0' cellspacing='4' cellpadding='4'\n" .
"\t\t\tstyle='padding-top:20px;'>\n";
print "\t\t<tr><td>Creation</td><td>Legs</td></tr>\n";
foreach ($rowsOfTable as $row) {
echo "\t\t<tr>\n" .
"\t\t\t<td>" . $row['name'] . "</td>\n" .
"\t\t\t<td align='right'>" . $row['count'] . "</td>\n" .
"\t\t</tr>\n";
}
print "\t</table>\n";
} catch (PDOException $ex) {
die ($ex->getMessage());
}
?>
Happy New Year, everybody :)
Is the style in dbc1.php preferred over dbc2.php? Why or why not?
The classes and functions used in the second sample ("dbc2") are from the old SQLite 2 functions. SQLite2 is old, and the extension has actually been pushed off to PECL. You should not use it in modern code unless you need to read a SQLite2 database.
You should use either the SQLite3 class or PDO, as demonstrated in your first sample ("dbc1").
Are the SQLite database files truly portable as claimed?
Yes, but not between major versions. You can transplant an SQLite3 database file between any machine and platform and have it work correctly.
May I have a pointer to PHP5-SQLite3 tutorial?
Because your best bet will be using PDO, you really actually want a PDO tutorial. The only ones out there are for MySQL. We frequently recommend this tutorial for users coming from the mysql_ functions, but some people also recommend this other PDO tutorial. Read both, just use SQLite-compatible SQL instead of MySQL-flavored SQL.
The SQLite site has a comprehensive syntax section that details what it does and does not understand. For the most part, you can just ditch the backticks and have things work properly. SQLite also doesn't like bundling index creation with table creation, but neither do many other databases.
Why do I get different version numbers from phpinfo() and sqlite_libversion()?
This is an artifact of having both the old SQLite 2 extension installed while also having the SQLite 3 PDO extension installed.

Categories