i have a simple php page that query the database for a random row (with some exceptions), every time it gets a post request.
i have noticed that the post request take some time to get the response.
because with every post request it reconnect to mysql server, so i thought maybe i could store the pdo in $_SESSION and use it to save some time and not have to authenticate with every request
i don't know if there is any way to fix this :)
<?php
// check for POST Request Only
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("HTTP/1.0 405 Method Not Allowed");
exit();
}
$host = 'localhost';
$db = 'Quiz';
$user = 'admin';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
if (!empty($_POST['old'])) {
$in = str_repeat('?,', count($_POST['old']) - 1) . '?';
$sql = "SELECT * FROM QT WHERE id NOT IN ($in) ORDER BY RAND() LIMIT 1";
$stm = $pdo->prepare($sql);
$stm->execute($_POST['old']);
$data = $stm->fetchAll();
echo json_encode($data);
exit();
} else {
$stm = $pdo->prepare('SELECT * FROM QT ORDER BY RAND() LIMIT 1');
$stm->execute();
$data = $stm->fetchAll();
echo json_encode($data);
exit();
}
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
Сonnecting to mysql database with every request is how
PHP intended to work
Nothing wrong here, nothing to optimize here.
Go connect on every request and next time try to optimize a real issue.
so i thought
Don't think. Measure.
From the experience I can tell you that its the query that takes the time, not the connection. But technically that would be a guess all the same. So you have to measure first, then get the real issue, then google for it, solutions are plenty.
But measure first.
Related
I created a function to connect to the db in php:
function fn_connect($is_write = false)
{
$host = '127.0.0.1';
$db = 'name_db';
if ($is_write) {
$user = 'user_write';
$pwd = 'password_write';
} else {
$user = 'user_read';
$pwd = 'password_read';
}
$conn = new mysqli($host, $user, $pwd, $db);
if ($conn->connect_error) {
die('The database is not available. Please, try again later.');
}
return $conn;
}
When I need to connect, im calling it (and closing it) like this
$conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
$conn->close();
I thought it will be a good idea to verify if the connection exists, that way, I guess, I save connecting to the db every time for nothing, like this:
if (!isset($conn)) $conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
if (isset($conn)) $conn->close();
Is this a good idea, a good practice? Should I jut connect normally and let Apache/PHP do the rest (no need to verify nothing)?
It is good practiose and good style to check the connection, before letting php try to get or send data.
What is not good style is to use die in your connection, because it leaves a broken page.
Better is to design the page so that page still works when the connection is broken.
My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.
I am Developing the simple application,the application related to database operations.
My doubt is how can i connect to multiple databases same time.
how can php knows which databases the data will store.
If the user enter the data which database it will enter,both databases or one database.
Please answer my question.i have struggling a lot for this question.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
Yes you can.. by using two connection strings..
$mysqli1 = new mysqli('HOST1', 'USER1', 'PASSWORD1', 'DB_NAME1');
$mysqli2 = new mysqli('HOST2', 'USER2', 'PASSWORD2', 'DB_NAME2');
and your queries should be like
$result1 = $mysqli1->query('query ......');
and
$result2 = $mysqli2->query('query ......');
Of course you can given example below add more connections if you want:
Class database
{
private oracleDatabase;
private mysqlDatabase;
public function connOracle() {
$db = "";
$user = "";
$password = "";
try {
$this->oracleDatabase = new PDO("oci:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Oracle). ". $e->getMessage();
}
}
public function connMysql() {
$db = "";
$user = "";
$password = "";
try {
$this->mysqlDatabase = new PDO("mysql:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Mysql). ". $e->getMessage();
}
}
}
Be carefull if you are using two databases on the same server at the same time. By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do
<?php
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
?>
then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !
You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
Use this below link to refer.What you have asked here.
PHP Documentation
Yes, you may use multiple database in one application, but the main thing is when you are communicating with the dbname, you have to specify that dbname also so than script will communicate with only that db in which you had defined. Ex.
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
$resultsa = mysql_query('SELECT * FROM table_a', $dbname) or die('Could not query database_a');
Yes you can connect multiple databases.
open your php.ini file and give me your database details like
port number,username,password.
And after that you can give the queries like this in your applications
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
Then to query database 1, do this:
mysql_query('select * from tablename', $dbh1);
and for database 2:
mysql_query('select * from tablename', $dbh2);
i think this is work fine for your question.
Yes you can, in very basic terms, you do it like this:
http://au1.php.net/function.mysql-connect
$conn = mysql_open($host, $username, $password, true);
To connect to multiple databases on the same server:
$dblink1 = mysql_select_db('database_a', $conn);
$dblink2 = mysql_select_db('database_b', $conn);
To get results from two databases:
$resultsa = mysql_query('SELECT * FROM table_a', $dblink1) or die('Could not query database_a');
$resultsb = mysql_query('SELECT * FROM table_b', $dblink2) or die('Could not query database_b');
edit - keep in mind that the mysql_ functions aren't available in recent PHP releases because they've been removed.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.
Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.
Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?