How to view how many MySQL queries ran on page load - php

I'm testing performance on a CMS I'm making, and I'm wondering is it possible to view what queries were ran on a page load. For example, let's say I run 'test.php'. When I go to it, a list of queries ran by mySQL show at the bottom of the page - is this possible? I've seen sites do this before.
Thanks

The function SHOW FULL PROCESSLIST will show the real-time and past history of all processes.
SHOW FULL PROCESSLIST
If you are using a server on which you have the rights to install packages, you can install mysqltop and test in real time file and MySQL resource usage and queries.

Well, if all your queries go through a function then it should be easy, but if each only uses the standard call, then it won't be. This also let's you switch to a different database type or something like that easily.
For instance on the CMS's I modified to be a library program, I have a DB Query function:
function db_query($qstring, $conn) {
$dbh = mysql_db_query($dbname,$qstring, $conn);
// this is where I would add some incrementing code, but it has to be global.
// or just do something like
if($_GET["debug"]=="debuginSQLcount"){
echo $qstring
}
return $dbh;
}
then to use it, I just do something like
$sql = "SELECT stuff";
}
$result = db_query($sql, $link);
if (!$result || db_numrows($result) < 1) {
If you do it like this, then just add a line to the function which increments a $GLOBALS variable or something like that. Read more at PHP global or $GLOBALS

Related

Passing function result into sqli

I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script

PHP DB caching, without including files

I've been searching for a suitable PHP caching method for MSSQL results.
Most of the examples I can find suggest storing the results in an array, which would then get included to page. This seems great unless a request for the content was made at the same time as it being updated/rebuilt.
I was hoping to find something similar to ASP's application level variables, but far as I'm aware, PHP doesn't offer this functionality?
The problem I'm facing is I need to perform 6 queries on page to populate dropdown boxes. This happens on the vast majority of pages. It's also not an option to combine the queries. The cached data will also need to be rebuilt sporadically, when the system changes. This could be once a day, once a week or a month. Any advice will be greatly received, thanks!
You can use Redis server and phpredis PHP extension to cache results fetched from database:
$redis = new Redis();
$redis->connect('/tmp/redis.sock');
$sql = "SELECT something FROM sometable WHERE condition";
$sql_hash = md5($sql);
$redis_key = "dbcache:${sql_hash}";
$ttl = 3600; // values expire in 1 hour
if ($result = $redis->get($redis_key)) {
$result = json_decode($result, true);
} else {
$result = Db::fetchArray($sql);
$redis->setex($redis_key, $ttl, json_encode($result));
}
(Error checks skipped for clarity)

How to periodically push data to the user interface in php

i need to implement a simple project using PHP and MySql in which i need to push data to the user's UI when some one else is updating the database, and i need to periodically do this too, so when some one else accessing the same table and modify it, another person who uses the UI can see the updates, sorry if i'm being silly but up to now i'm only aware of saving data to a database and retrieving and showing it to the user(simplest form of data base connection). how can i achieve this in php, please some one help me on this matter, if the answer explains the things in detail it is good, because i'm very novice to this.thanks in advance.
rangana.
If the web page has no data to return, then get the page to wait for a period while polling the database. You must use the sleep statement to avoid maxing out your server.
Warning: Some servers wont let the user open another page while one is in progress, which may cause you problems in some situations. So either dont hold the page open for too long, or maybe try to get the ajax page to use a different session.
// do this when you have put new data in to database
setappdata("lastupdate",microtime(true));
// use this loop to poll for new data
$loop = 0;
$lastupdate=$_SESSION["lastupdate"];
while ($lastupdate==$last=getappdata("lastupdate") and $loop<10) {
$loop++;
usleep(500000); //0.5sec
}
// use a table called appdata to store application data
function getappdata($var) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)<1) return false;
return mysql_result($res1,0,"data");
}
function setappdata($var,$data) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)>0) $query = "UPDATE appdata SET data='$data' WHERE var='$var'";
else $query = "INSERT INTO appdata SET var='$var',data='$data'";
return mysql_query($query);
}
These topics may get you started:
http://en.wikipedia.org/wiki/Push_technology
http://en.wikipedia.org/wiki/Reverse_Ajax

mysql data being inserted twice via php

I can't for the life of me figure out why this function is causing multiple entries into my database table...
When I run the function I end up with two records stacked on top of each one second apart
screen cap http://img132.imageshack.us/img132/5053/screenshot20100517at259.png
here is the function:
function generate_signup_token(){
$connection = new DB_Connect(); // <--- my database connection class
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$sign_up_token = uniqid(mt_rand(), true);
$_SESSION['signup_token'] = $sign_up_token;
$sign_up_token = mysql_real_escape_string($sign_up_token);
$query = "INSERT INTO `token_manager` (`ip_address`, `signup_token`) VALUES ('$ip', '$sign_up_token')";
mysql_query($query);
}
generate_signup_token();
The biggest piece of evidence that this function is being called more than once is the different signup tokens that are being generated.
Also, there is a one second difference between inserts which may be indicative of multiple page requests. If there is consistently such a time disparity, I'd investigate the access log. If there's only one page request, then the function must be called more than once somehow.
It looks like your function is fine. It appears that you are somehow calling the function twice. I'd suggest adding some debugging information to the function to figure out why. The function debug_print_backtrace might come in handy for this.

Web page installer - database deployment

I have the website written in PHP (Kohana) and MySQL. I want to create the installer which would run all the environment tests and, what is the most important (and the most misterious) for me, will deploy the database. What is more, I would like to choose the prefix of the tables in the database and specify the username and password for the admin. Would you please give my some hints how to do it? Or some link to some tutorial? I was trying to google that but when I searched for terms like "PHP website installer" I have found only how to install PHP.
The most important for me is the process of deploying database with user-defined tables prefix. How should I store the database structure in the file. Should I name the tables using some keyword for the prefix, for example:
%%prefix%%_tableName
or
__prefix__tableName
And what then? Change all the keywords using regular expresions? Is it correct way or is it any better?
A simple way would be to store the SQL queries in PHP files and have PHP inject the prefix into the SQL and return the string.
Like, if you had a PHP file like this for each of your CREATE TABLE queries:
<?php
/** get_myTable.php **/
return <<<SQL
CREATE TABLE `{$prefix}myTable` ( ... )
SQL;
?>
You could do this in your main code:
<?php
$prefix = 'dbprefix_';
$create_queries = array();
$create_queries[] = include('get_myTable.php');
$create_queries[] = include('get_otherTable.php');
foreach($create_queries as $_query) {
mysql_query($_query) or trigger_error(mysql_error(), E_USER_WARNING);
}
?>
Wordpress has its famous '5-minute install'. It's a great benchmark for simplicity, usability, and power and it does most, if not all, of the things you outlined in your question.

Categories