php Getting Data from Database slows down the Page - php

I am using wamp server on windows. while getting a little bit of data from my database hangs my page badly. it's just like a simple post which have 1 image 1 title and a little bit discription and when I trigger the command it hangs my page badly. here is how my code looks like.
<?php
//1. Create a connection
$connection= mysql_connect("localhost","root","");
if(!$connection){
die("Database Connection Failed :" . mysql_error());
}
//2 Select a database to use
$db_select = mysql_select_db("gat", $connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
<html>
<head>
<title>Database Check</title>
</head>
<body>
<?php
//3 perform database query
$result=mysql_query("SELECT * FROM recent_works",$connection);
if (!$result) {
die("Database query failed:" . mysql_error());
}
//4 use returned data
while ($row= mysql_fetch_assoc($result)) {
echo "<div class='work_item'>";
echo "<img src='{$row['image']}' alt=''>";
echo "<h2>{$row['title']}</h2>";
echo "<p>{$row['short_discription']}</p>";
echo "</div>";
}
?>
</body>
</html>
<?php
//5 close connection
mysql_close($connection);
?>

Fetching data from a database will always involve some level of blocking. The question is how much data are you fetching. Your example indicates you are selecting everything from the table and fetching all of the data to print out onto the page. So how many rows are in the table, how much data is stored in each column, and how much of that data gets transferred to the client are all provisioning factors of speed here. Additionally, you have to consider that connecting to the database also has a cost.
Here are a few suggestions I can make to the above code:
Don't use the old mysql extension (mysql_* functions), but consider using the newer MySQLi extension, which can help you do things the old extension can't; like asynchronous queries. It's also highly discouraged to use the old mysql extension in new development, since it's in plans for deprecation currently. See MySQL: choosing an API in the PHP manual for more information.
Check phpinfo() to make sure you aren't using output buffering (which requires buffering up to a certain amount of data before it gets sent to the client). This could result in the client waiting around until there's data ready to be sent. Pushing some HTML content out to the client as soon as possible could help improve the user experience.
Don't use SELECT * FROM table in your queries, instead, consider explicitly selecting only the fields you need for each query: SELECT image,title,short_discription FROM recent_works
If there's a lot of data (more than say hundred rows maybe) consider using pagination and LIMIT the query to a certain number of rows per page view. This can greatly reduce the amount of traffic between your DBMs and PHP on a per request basis.
If it's a high load site consider using a persistent database connection.

Related

How to connect to database and get custom data in Phorum?

I am using the external authentication system. Therefore, there are a lot of user data, which is not available in Phorum.
I am using the last post module, although I want to get the information from the last post user, from my own user table (I have some data, like avatar, birth info etc). I want to show in my Phorum. How can I achieve this?
I've tried to simply connect via a: mysql_query(); but then I just get No database selected error.
I've searched for hours - I cannot find any documentation regarding getting custom data from your own user table.
I would recommend using mysqli, as mysql is deprecated. First make sure that your connection is correct. No database selected means you probably do not have your connection included at the top.
$con = mysqli_connect("localhost","username","password","database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error());
}
Make sure that your sql statement looks like so (Notice the $con in the mysqli_query()):
$sql = "select * from TableName";
if ($que = mysqli_query($con, $sql)) {
// Query has ran
}

execute mysql query and display results while reading

I have a mysql database and i want to execute a query and while this query is being executed the data should be displayed in page.
so for example if i have 1,000 result row from the query result i want to display each row while the query is being executed instead of waiting till the query finishes executing then displaying them at once.
here is my php code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Database Name
mysql_select_db("dbname", $con);
$test_query = mysql_query("SELECT * FROM V_Posts where _PID > 100 and _PID < 10000");
while($CHECK_PCID_R = mysql_fetch_array($test_query))
{
echo $CHECK_PCID_R['_PID'] . "<br />";
}
?>
I tried
echo $CHECK_PCID_R['_PID'] . "<br />";
flush();
But it didn't work :(
One query will produce one dataset and you'll have all the data at once. If your query is slow any latency in displaying the data will be small compared to the delay in receiving it. Using flush() might force the server to send parts of the page, but you're really just tinkering at the edges.
If you want to break this down you'll have to run multiple queries, which will arguably be much slower since you'll be running the same query repeatedly. This will load the database server unnecessarily, and will achieve only a minor cosmetic effect.
If you use an AJAX call to retrieve your data you can display a 'loading' message while you wait. You could use multiple AJAX calls to display the data bit by bit - this is even worse than using multiple queries in the PHP script.

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

connecting to a database using HostMonster

I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.

PHP to MySQL beginner question:

Just to get started, and thinking I needed a "database," I did this:
$db = new PDO("java:comp/env/jdbc/mysql");
$stmt = $db->query("CREATE DATABASE kitty_db");
To see if it worked I commented out the above and then wrote:
$link = mysql_connect('localhost:3306', 'me', 'blah');
$db_list = mysql_list_dbs($link);
while($row = mysql_fetch_object($db_list)) {
echo $row->Database ."<BR>";
And I saw that my new database was there:
information_schema
mysql
kitty_db
performance_schema
test
And so my first question is, did I even need to make a new database next to mysql just to get started on something? I don't recall ever having to do that a couple of years ago (7 actually) when I was setting up MySQL before (sans via PHP).
Anyway, I'm wondering why I can't create a table now. If kitty_db isn't a good idea, let's take it out. But I may be having trouble putting a TABLE 'milk_bowl' (with an index or key or whatever 'bowl_name' field).
Thanks for any help. Things have gotten more complex since I just opened up a command line in MySQL almost a decade ago and just issued simplistic queries.
And so my first question is, did I
even need to make a new database next
to mysql just to get started on
something? I don't recall ever having
to do that a couple of years ago (7
actually) when I was setting up MySQL
before (sans via PHP).
This question is kind of vague. You are asking about needing to make a database to start on something? Without know more about your something, I don't really think that question is answerable. Creating the database is usually the first step when setting up a database. You might find this helpful when getting started.
Anyway, I'm wondering why I can't
create a table now. If kitty_db isn't
a good idea, let's take it out. But I
may be having trouble putting a TABLE
'milk_bowl' (with an index or key or
whatever 'bowl_name' field).
From the above link (adapted to your example):
<?php
$con = mysql_connect("localhost:3306","me","blah");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE kitty_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("kitty_db", $con);
$sql = "CREATE TABLE milk_bowl
(
bowl_name varchar(15),
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Thanks for any help. Things have
gotten more complex since I just
opened up a command line in MySQL
almost a decade ago and just issued
simplistic queries.
I don't think that's changed all that much. You can still use the command line to connect to your mysql db and issue queries directly. PHP just lets you do it through a browser/scripts.
This is not a direct answer to your question, but it might solve your problem... have you tried using an application such as MySQL Administrator or MySQL Query Browser? I came back to MySQL recently after a very long hiatus as well and found them both very helpful.

Categories