mysql – CodeForest https://www.codeforest.net Mon, 01 Sep 2025 13:47:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://www.codeforest.net/wp-content/uploads/2017/06/cropped-Asset-3-32x32.png mysql – CodeForest https://www.codeforest.net 32 32 jQuery Mobile Advanced Tutorial – RSS reader app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-advanced-tutorial-rss-reader-app https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app#comments Tue, 23 Aug 2011 06:59:38 +0000 https://www.codeforest.net/?p=970 Today’s tutorial is going to show you how you can use jQuery Mobile with PHP, MySQL and a bit of AJAX to build a small mobile web application.

At the end of this tutorial you will know how to add new RSS feed name and url into the database, how to delete the record from the database, how to fetch and parse a RSS feed and show its results inside jQuery Mobile list view.

If you are not familiar with jQuery Mobile, I suggest you read my jQuery Mobile basic tutorial and then come back.

So, let’s start. Many things in our RSS reader application will take place inside our index.php file. The front page of the application will have links for creating new RSS feed and Read existing feeds.

First of all we need a database table to store our feeds in. Create one using this SQL code:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
[/code]

Now, I will create a db.php which will have a database connection and some basic functions for database handling. Create folder named inc and put your db.php file in it with this code pasted:

[code lang=”php”]
/*** mysql hostname ***/
$hostname = ‘localhost’;

/*** mysql username ***/
$username = ‘root’;

/*** mysql password ***/
$password = ”;

$dbname = ‘demo’;

try
{
mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
}
catch (Exception $e)
{
// normally we would log this error
echo $e->getMessage();
}

function db_select_list($query)
{
$q = mysql_query($query);
if (!$q) return null;
$ret = array();
while ($row = mysql_fetch_array($q, MYSQL_ASSOC)) {
array_push($ret, $row);
}
mysql_free_result($q);
return $ret;
}

function db_select_single($query)
{
$q = mysql_query($query);
if (!$q) return null;
$res = mysql_fetch_array($q, MYSQL_ASSOC);
mysql_free_result($q);
return $res;
}
[/code]

This is a pretty basic code for connecting and fetching records from our database.

To keep things organized, I will put my header section inside external PHP file. Inside inc folder create file named header.php, then paste this in the header file:

[code lang=”php”]




Codeforest jQuery Mobile Tutorial



[/code]

This is basic HTML 5 header with included jQuery and jQuery Mobile.

Now create a file in your root directory and name it index.php and paste this in it:

[code lang=”php”]

Welcome!

CodeForest



[/code]

Save everything and try it in your browser. Pretty cool.

As you can see our links to other pages look like anchor links. I am going to have multiple pages inside my index.php file and that is the way to link to them.

Now paste this whole code inside index.php overwriting the previous code:

[code lang=”php”]

Welcome!

CodeForest

Add New RSS Feed

Back



Codeforest

RSS Feeds

Back

CodeForest



[/code]

Above code is pretty simple. There are 3 pages, the indexPage, addFeedPage and readFeedPage. As we firstly have to add some feeds to read, let me show you how to do it.

As you can see, the AddNewFeedPage is basically a form for collecting New feed data (Feed name and Feed URL). Open your index.php in browser and click on Create New Feed link. You should see the form.

Now, add this JavaScript code directly before the closing body tag in your index.php file:

[code lang=”javascript”]

[/code]

Above code is catching Submit button click event and making an AJAX call to addFeed.php file which will handle the database writing. Create an addFeed.php file and paste this in:

[code lang=”php”]
getMessage();
}
[/code]

We are including our database file, sanitizing user input (you should never trust user entered data and always sanitize it!) and finally writing our entry in database. Now, go and add your RSS feed and save it. Make sure the feed URL is correct.

Now go back to your home page and click on Read RSS feeds link. You should see a feed name you just entered. Let me show you how to fetch and parse this feed.

Create a file named feed.php in your root directory and paste this in:

[code lang=”php”]
feedData.php in your root folder and paste this in:

[code lang=”php”]




[/code]

This code is rendering the view. First we check if feed is valid and if it is parsing it using SimpleXMLElement. Go ahead and try it. If everything worked, you should see 10 titles from the feed which are links to the actual articles.

If something is wrong with the feed format and it is not in RSS feed format, you will get a nice message.

Notice the Delete button on top right. It is used so you can delete the feed you are viewing from the database. Create deleteFeed.php and paste the code for deleting in:

[code lang=”php”]

I hope that this tutorial showed how easy it is to build mobile web applications using jQuery Mobile, PHP and MySQL.

Do you like jQuery Mobile? Are you using it or plan to use it? Do not hesitate to discuss in our comment section below. And if you have any questions, I will gladly answer them.

Stay tuned.

]]>
https://www.codeforest.net/jquery-mobile-advanced-tutorial-rss-reader-app/feed 11
8 great MySQL Performance Tips https://www.codeforest.net/8-great-mysql-performance-tips?utm_source=rss&utm_medium=rss&utm_campaign=8-great-mysql-performance-tips Tue, 15 Mar 2011 20:47:01 +0000 https://www.codeforest.net/?p=782 You finished your brand new application, everything is working like a charm. Users are coming and using your web. Everybody is happy.

Then, suddenly, a big burst of users kills your MySQL server and your site is down. What went wrong? How can you prevent it?

Here are some tips on MySQL Performance which will help you and help your database.

Think BIG

In the early stage of development you should be aware of expected number of users coming to your application. If you expect many users, you should think big from the very beginning, plan for replication, scalability and performance.

But, if you optimize your SQL code, schema and indexing strategy, maybe you will not need big environment. You must always think twice as performance and scalability is not the same.

Always use EXPLAIN

The EXPLAIN statement can be used either as a way to obtain information about how MySQL executes a SELECT statement or as a synonym for DESCRIBE.

When you precede a SELECT statement with the keyword EXPLAIN, MySQL displays information from the optimizer about the query execution plan. That is, MySQL explains how it would process the SELECT, including information about how tables are joined and in which order. EXPLAIN EXTENDED can be used to provide additional information.

Choose the right data type

Databases are typically stored on disk (with the exception of some, like MEMORY databases, which are stored in memory). This means that in order for the database to fetch information for you, it must read that information off the disk and turn it into a results set that you can use. Disk I/O is extremely slow, especially in comparison to other forms of data storage.

When your database grows to be large, the read time begins to take longer and longer. Poorly designed databases deal with this problem by allocating more space on the disk than they need. This means that the database occupies space on the disk that is being used inefficiently.

Picking the right data types can help by ensuring that the data we are storing makes the database as small as possible. We do this by selecting only the data types we need.

Use persistent connections

The reason behind using persistent connections is reducing number of connects which are rather expensive, even though they are much faster with MySQL than with most other databases.

There are some debate on the web on this topic and mysqli extension has disabled persistent connection feature, so I will not write much more on this topic. The only downside of persistent connections is that if you have many concurrent connections, max_connections setting could be reached. This is easily changed in Apache settings, so I don’t think this is the reason why you should not use persistent connections.

Persistent connections are particularly useful if you have db server on another machine. Because of the mentioned downside, use them wisely.

Learn about Query Cache

The query cache stores the text of a SELECT statement together with the corresponding result that was sent to the client. If an identical statement is received later, the server retrieves the results from the query cache rather than parsing and executing the statement again. The query cache is shared among sessions, so a result set generated by one client can be sent in response to the same query issued by another client.

The query cache can be useful in an environment where you have tables that do not change very often and for which the server receives many identical queries. This is a typical situation for many Web servers that generate many dynamic pages based on database content.

The query cache does not return stale data. When tables are modified, any relevant entries in the query cache are flushed.

How do you find out my MySQL query cache is working or not?
MySQL provides the stats of same just type following command at mysql> prompt:

mysql> show variables like 'query%';

Do not use indexed column in a function

Index on a column can be great performance gain, but if you use that column in a function, index is never used.

Always try to rewrite the query to not use the function with indexed column.

WHERE TO_DAYS(CURRENT_DATE) - TO_DAYS(event_date) >= 7

could be

WHERE event_date >= '2011/03/15' - INTERVAL 7 DAYS

and today’s date is generated from PHP. This way, index on column event_date is used and the query can be stored inside Query Cache.

Learn the Zen of SQL coding

SQL code is the foundation for optimizing database performance. Master SQL coding techniques like rewriting subquery SQL statements to use JOINS, eliminating cursors with JOINS and similar.

By writing great SQL code your database performance will be great.

Use ON DUPLICATE KEY UPDATE

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.

INSERT INTO wordcount (word, count)
VALUES ('a_word',1)
ON DUPLICATE KEY UPDATE count=count+1;

You are saving one trip to the server (SELECT then UPDATE), cleaning you code up removing all if record_exists insert else update.

If you follow some of this tips, database will be greatful to you.

]]>
6 useful MySQL queries https://www.codeforest.net/6-useful-mysql-queries?utm_source=rss&utm_medium=rss&utm_campaign=6-useful-mysql-queries https://www.codeforest.net/6-useful-mysql-queries#comments Wed, 29 Dec 2010 21:23:40 +0000 https://www.codeforest.net/?p=703 The art of query building is the art of using Structured Query Language to formulate correct, efficient database questions and commands. In SELECT queries, you can use JOIN, WHERE and HAVING clauses to scope the result to specific rows and columns, GROUP BY to combine result rows into analytic summaries, and UNION to combine the results of multiple queries. INSERT, DELETE and UPDATE commands may reference JOINs. INSERT … SELECT inserts a query result into another table. DELETEs and UPDATEs may be scoped by WHERE clauses.

1. Age in years

You have a birth date and need to calculate how old is the guy. Assume the @dateofbirth is this date:

SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;

2. Difference between two dates

Find the difference between two datetime values in seconds, minutes, hours or days. If dt1 and dt2 are datetime values of the form ‘yyyy-mm-dd hh:mm:ss’, the number of seconds between dt1 and dt2 is

UNIX_TIMESTAMP( dt2 ) - UNIX_TIMESTAMP( dt1 )

To get the number of minutes divide by 60, for the number of hours divide by 3600, and for the number of days, divide by 3600 * 24.

3. Display column values which occur N times

SELECT id
FROM tbl
GROUP BY id
HAVING COUNT(*) = N;

4. Count business days between two dates

The simplest support for counting business days between any two dates is a calendar table with columns d date and holiday bool populated for all days in all possibly relevant years. Then the following query gives the inclusive number of business days between dates Start and Stop:

SELECT COUNT(*)
FROM calendar
WHERE d BETWEEN Start AND Stop
AND DAYOFWEEK(d) NOT IN(1,7)
AND holiday=0;

5. Find primary key of the table

SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING (constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
AND t.table_schema='db'
AND t.table_name='tbl'

6. Find out how big is your database

SELECT
table_schema AS 'Db Name',
Round( Sum( data_length + index_length ) / 1024 / 1024, 3 ) AS 'Db Size (MB)',
Round( Sum( data_free ) / 1024 / 1024, 3 ) AS 'Free Space (MB)'
FROM information_schema.tables
GROUP BY table_schema ;

I hope that this not so common queries will help you out.

]]>
https://www.codeforest.net/6-useful-mysql-queries/feed 9
Making a shoutbox with PHP, MySql and jQuery – Revisited https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited?utm_source=rss&utm_medium=rss&utm_campaign=making-a-shoutbox-with-php-mysql-and-jquery-revisited https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited#comments Wed, 13 Oct 2010 19:46:21 +0000 https://www.codeforest.net/?p=517 Recommendation to all my readers who have trouble with their hosting not installing PDO: change your hosting.

This is just an update on a previous tutorial which can be found here.

In that particular tutorial I am using PDO class to manipulate the MySql database. Everything else stays the same, except the code in shout.php file.

For all readers that can not use PDO, change the code in shout.php to this:


/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

$dbname = 'demo';

mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);

if($_POST['name']) {
	$name = mysql_real_escape_string($_POST['name']);
	$message = mysql_real_escape_string($_POST['message']);

	$sql = "INSERT INTO shoutbox (date_time, name, message)
	VALUES (NOW(), '".$name."', '".$message."')";

		/*** run the sql statement ***/
		if (mysql_query($sql)) {
			populate_shoutbox();
		}
	}

	if($_POST['refresh']) {
		populate_shoutbox();
	}

	function populate_shoutbox() {
		$sql = "select * from shoutbox order by date_time desc limit 10";
		$rez = mysql_query($sql);
		echo '
		<ul>
		<li style="list-style-type: none;">
		<ul>';</ul>
		</li>
		</ul>
		<ul>
		<li style="list-style-type: none;">
		<ul>while ($row = mysql_fetch_array($rez, MYSQL_ASSOC)) {</ul>
			</li>
			</ul>
			<ul>
			<li style="list-style-type: none;">
			<ul>echo '
			<li>';
			echo '<span class="date">'.date("d.m.Y H:i", strtotime($row['date_time'])).'</span>';
			echo '<span class="name">'.$row['name'].'</span>';
			echo '<span class="message">'.$row['message'].'</span>';
			echo '</li>
			</ul>
			</li>
			</ul>
			';
		}
		echo '

		';
	}

Now your shoutbox is working like a charm using mysql functions.

]]>
https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited/feed 4
jQuery Live Login inspired by Google Instant Search https://www.codeforest.net/jquery-live-login-inspired-by-google-instant-search?utm_source=rss&utm_medium=rss&utm_campaign=jquery-live-login-inspired-by-google-instant-search https://www.codeforest.net/jquery-live-login-inspired-by-google-instant-search#comments Tue, 28 Sep 2010 21:00:38 +0000 https://www.codeforest.net/?p=469 We visit thousands of web pages and log in to hundreds of them. Always the same thing is repeating every single time. You enter username, press tab, enter password, press Enter key or click on a button.

I was inspired by Google Instant Search and I will demonstrate how we can build log in functionality without having to press Enter or click a button. This is fairly simple task and using jQuery and a touch of PHP, we can achieve this in no time.

You can see the finished script in action below:


We will need a simple database table for our user data. Something like this:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM ;


— Dumping data for table `users`

INSERT INTO `users` (`id`, `name`, `username`, `password`) VALUES
(1, ‘Demo’, ‘demo’, ‘demo123’);
[/code]

Next, we will build a login form:

[code lang=”html”]

Username:

Password:

[/code]

As you can see, I created a div with id of message, which will hold the response from server later on.

Let’s create some jQuery magic:

[code lang=”javascript”]
$(function() {
$(‘#password’).keyup(function() { // when we release the key
var pass = $(‘#password’).val();
if(pass.length >= 3) { // if there are more then 3 letters
var data = ‘username=’+ $(“#username”).val() + ‘&pass=’ + pass;
// ajax call
$.ajax({
type: “POST”,
url: “login.php”,
data: data,
success: function(html){ // this happen after we get result
if(html !== ”) {
$(“#form”).hide(); // hiding form
$(“#message”).append(html);
$(“#message”).fadeIn(800);
}
}
});
}
});
});
[/code]

This code is triggered after a key has been released on password field. It counts the characters, and as soon as there are 3 or more of them, it sends an AJAX request to login.php file which looks like this:

[code lang=”php”]
if($_POST) {

/*** mysql hostname ***/
$hostname = ‘localhost’;

/*** mysql username ***/
$username = ‘root’;

/*** mysql password ***/
$password = ”;

$dbname = ‘demo’;

try {
$dbh = new PDO(“mysql:host=$hostname;dbname=$dbname”, $username, $password);
// getting and escaping POST variables
$user = addslashes(strip_tags($_POST[‘username’]));
$pass = addslashes(strip_tags($_POST[‘pass’]));

/*** set all errors to execptions ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/*** checking username and password ***/
$sql = “SELECT count(*) AS total FROM users
WHERE username = :user AND
password = :pass”;
$stmt = $dbh->prepare($sql);
/*** bind the paramaters ***/
$stmt->bindParam(‘:user’, $user, PDO::PARAM_STR);
$stmt->bindParam(‘:pass’, $pass, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->fetch(PDO::FETCH_COLUMN) > 0) {
$sql = “SELECT * FROM users
WHERE username = :user AND
password = :pass”;
$stmt = $dbh->prepare($sql);
/*** bind the paramaters ***/
$stmt->bindParam(‘:user’, $user, PDO::PARAM_STR);
$stmt->bindParam(‘:pass’, $pass, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// here we write $row to $_SESSION
$_SESSION[‘User’] = $row;
// sending user’s name back as result
echo ‘

Congratulations, ‘ . $row[‘username’] . ‘, you have successfuly logged in!

‘;
}
}
catch(PDOException $e) {
echo $e->getMessage();
}

}
[/code]

This is simple, we are declaring some db connection variables at the top, then connecting to database using PDO class. Then we count rows from the database where username and password match those entered in the form. If there is no such user in the database, nothing happens, but if we find such a user PDO fetches user data from database and store it to the SESSION. At the end, we are sending a nice message back to the Javascript as response.

jQuery scripts is controlling the response, and as soon as it is not empty, it is hiding the form and appending our response message to message div.


I would like to see your opinion on using this method on a live site, so do not hesitate to comment. This is an experiment and probably not so good to use on login form, but interesting to play with.

]]>
https://www.codeforest.net/jquery-live-login-inspired-by-google-instant-search/feed 17
Making a shoutbox with PHP, MySQL and jQuery https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery?utm_source=rss&utm_medium=rss&utm_campaign=making-a-shoutbox-with-php-mysql-and-jquery https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery#comments Mon, 13 Sep 2010 21:12:17 +0000 https://www.codeforest.net/?p=397 Wikipedia says that : “A shoutbox, saybox, tagboard, or chatterbox is a chat-like feature of some websites that allows people to quickly leave messages on the website, generally without any form of user registration.”

I am going to show how you can easily build one of those, add some fancy awesomeness to it using jQuery AJAX. As the definition says, we need a simple form in which the user will enter his name and message. After the user submits the form, we will send the data through AJAX to our server side script, which will insert it into database and refresh the shoutbox. But, we have to refresh it for other users, too. I will show you how in the end of this tutorial. Check out the demo below and return to read the rest.

First, we will create a database table to hold our shoutbox data:

CREATE TABLE IF NOT EXISTS `shoutbox` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_time` datetime NOT NULL,
`name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM

As I said, we need a simple form, so here is our markup:

<h2>Shoutbox</h2>
<form method="post" action="shout.php">Name: <input type="text" id="name" name="name" />
	Message: <input type="text" id="message" name="message" class="message" />
	<input type="submit" id="submit" value="Submit" />
</form>
<div id="shout"></div>

Simple form and a div with id of shout, which will hold our shoutbox data. So, let me show you the jQuery code which will juice everything up and do the shouting magic:

$(function() {

	$("#submit").click(function() {
		// getting the values that user typed
		var name = $("#name").val();
		var message = $("#message").val();
		// forming the queryString
		var data = 'name='+ name +'&amp;message='+ message;

		// ajax call
		$.ajax({
			type: "POST",
			url: "shout.php",
			data: data,
			success: function(html){ // this happen after we get result
			$("#shout").slideToggle(500, function(){
				$(this).html(html).slideToggle(500);
				$("#message").val("");
			});
		}
	});
	return false;
});
});

I commented everything above, so go ahead and read it carefully. This code is collecting what user typed and sending it to server side script shout.php, empties the shout div and appending the new content. The return false is used so the form is not actually submitted.

On the server side I will show you how to use the PDO extension to securely issue the insert statement and some other magical things.

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.

So here is our shout.php file:

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

$dbname = 'shout';

try {
	$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

	if($_POST['name']) {
		$name = $_POST['name'];
		$message = $_POST['message'];
		/*** set all errors to exceptions ***/
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$sql = "INSERT INTO shoutbox (date_time, name, message)
		VALUES (NOW(), :name, :message)";
		/*** prepare the statement ***/
		$stmt = $dbh->prepare($sql);

		/*** bind the params ***/
		$stmt->bindParam(':name', $name, PDO::PARAM_STR);
		$stmt->bindParam(':message', $message, PDO::PARAM_STR);

		/*** run the sql statement ***/
		if ($stmt->execute()) {
			populate_shoutbox();
		}
	}
}
catch(PDOException $e) {
	echo $e->getMessage();
}

/***** I WILL EXPLAIN THIS LATER *****/
if($_POST['refresh']) {
	populate_shoutbox();
}
/********************************/

function populate_shoutbox() {
	// so we don't have to connect again
	global $dbh;
	$sql = "select * from shoutbox order by date_time desc limit 10";
	echo '
	<ul>
		<li style="list-style-type: none;">
			<ul>';</ul>
		</li>
	</ul>
	<ul>
		<li style="list-style-type: none;">
			<ul>foreach ($dbh->query($sql) as $row) {</ul>
		</li>
	</ul>
	<ul>
		<li style="list-style-type: none;">
			<ul>echo '
				<li>';
					echo '<span class="date">'.date("d.m.Y H:i", strtotime($row['date_time'])).'</span>';
					echo '<span class="name">'.$row['name'].'</span>';
					echo '<span class="message">'.$row['message'].'</span>';
				echo '</li>
			</ul>
		</li>
	</ul>
	';
}
echo '

';
}

Let me explain a bit. First we are declaring some variables for db connection.

$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

This is the actual connection to the database. It also selects the database (similar to mysql_selectdb).

Now that you’re connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you’ve never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman’s terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven’t already committed it), which makes error handling in your scripts easier.

Transactions are typically implemented by “saving-up” your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).

The interesting part is preparing statement for inserting into database. This is a higher level of security. The parameters to prepared statements don’t need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur.

Other great advantage is that the query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle.

Our populate_shoutbox function is selecting the last 10 rows entered in the database and populate the Unordered list on the client side.

Now, you remember that I said that we will refresh the data for other users, so they can see what you actually typed in without the need to refresh the page.

On the client side I will add one function to the game. Its purpose is to populate the shoutbox the first time you arrive, and then it will fetch new data every 15 seconds. This is ok, as this is not chat.

function refresh_shoutbox() {
	// we need some post data
	var data = 'refresh=1';

	$.ajax({
		type: "POST",
		url: "shout.php",
		data: data,
		success: function(html){ // this happen after we get result
		$("#shout").html(html);
	}
});
}

//populating shoutbox the first time
refresh_shoutbox();
// recurring refresh every 15 seconds
setInterval("refresh_shoutbox()", 15000);

And that is what the lines:

if($_POST['refresh']) {
    populate_shoutbox();
}

in shout.php are doing. If $_POST[‘refresh’] is received, it simply call the populate_shoutbox function.

This is it. I showed you how easy it is to implement the shoutbox functionality and why you should use the PDO extension to communicate with the database. In some tutorial to come, we will build a complete class for database operations using the PDO extension. So, stay tuned.

]]>
https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery/feed 7
Key/value tables and how to use them in PHP and MySQL https://www.codeforest.net/keyvalue-tables-and-how-to-use-them-in-php-and-mysql?utm_source=rss&utm_medium=rss&utm_campaign=keyvalue-tables-and-how-to-use-them-in-php-and-mysql https://www.codeforest.net/keyvalue-tables-and-how-to-use-them-in-php-and-mysql#comments Thu, 09 Sep 2010 12:03:05 +0000 https://www.codeforest.net/?p=371 Today’s subject is a little bit advanced, but I think that beginners should be able to follow if they read carefully.

Key/value approach in database design could come in handy when we need to store some arbitrary data about another table. For example, we have a users table that holds our user data. Everything is working fine, but some day our client decides that he wants to collect 2 telephone numbers, sex of the user, date of birth …

If we try to predefine all the potential wishes of the customer in our table, it would be awkward and our table would grow horizontally beyond reason.

Here comes key/value table to the rescue. Let us create a users table (as simple as it can be):

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM ;

[/code]

This table will hold nothing but a login data. Let us create a user_data table which will hold everything else:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS`user_details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`key` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
[/code]

The fields key and value will actually store the user data. Because this table is going to grow vertically, potentially we can store an unlimited and completely arbitrary information about a user. Two different parts of your app can handle storing the user details completely independent of each other. This is the power of this approach.

This approach is highly flexible, adding a new attribute at a late design phase is very simple. We can even create a mechanism that adds attributes according to real time configuration.

Enough about good sides, let me talk about drawbacks of this design. One major drawback is that there is no database data types in our user_data table. For example, consider this statement:

[code lang=”sql”]
UPDATE user_data SET value = ‘What?’ WHERE key = ‘date_of_birth’
[/code]

We are setting a string value for a key that should hold user’s date of birth. Of course, this can be handled through data validation on the application side, so it is not such a drawback.

A bigger problem is if we use user_data table for filtering. Imagine that we have only one users table with all the fields and need to retrieve all users that live in Chicago. In classic database design this would be the query:

[code lang=”sql”]
SELECT username FROM users WHERE city = ‘Chicago’
[/code]

Simple. But in our new key/value database design this query would look like this:

[code lang=”sql”]
SELECT username FROM users a
INNER JOIN user_data b
ON a.id = b.user_id
WHERE b.key = ‘city’
AND b.value = ‘Chicago’
[/code]

Pretty complex for such an easy task. Wait till you see this example. What if you need to filter data by 2 criteria. For example in classic design:

[code lang=”sql”]
SELECT username FROM users WHERE city = ‘Chicago’ AND state = ‘Illinois’
[/code]

In key/value design you can easily fall in the, so called, AND trap. At fist glance everybody will say: This is easy and type something like this:

[code lang=”sql”]
SELECT username FROM users a
INNER JOIN user_data b
ON a.id = b.user_id
WHERE
(b.key = ‘city’ AND b.value = ‘Chicago’)
AND
(b.key = ‘state’ AND b.value = ‘Illinois’)
[/code]

But this query will ALWAYS return nothing. Zero. Nada. That is because there is never ONE row in user_data that has both criteria met. So, now this complex query becomes monster:

[code lang=”sql”]
SELECT username FROM users a
INNER JOIN user_data b
ON a.id = b.user_id
INNER JOIN user_data c
ON b.user_id = c.user_id
WHERE
(b.key = ‘city’ AND b.value = ‘Chicago’)
AND
(c.key = ‘state’ AND c.value = ‘Illinois’)
[/code]

Conclusion is that this approach is great but must be used with caution. I would mainly use it for storing some arbitrary data that will never be used for filtering.

]]>
https://www.codeforest.net/keyvalue-tables-and-how-to-use-them-in-php-and-mysql/feed 16
Cache for your database queries https://www.codeforest.net/cache-for-your-database-queries?utm_source=rss&utm_medium=rss&utm_campaign=cache-for-your-database-queries https://www.codeforest.net/cache-for-your-database-queries#comments Thu, 22 Apr 2010 21:26:33 +0000 https://www.codeforest.net/?p=80 When there is a lot of people on your site, they read many articles (which is good). That leads to big number of database retrievals and your database is potential bottleneck (which is bad).

So what will we do about it? The best way is to cache the database results, so when first user reads an article, it is fetched from the database, but when the same article is requested again, then we read it from the cache and thus allowing our MySql server to rest a bit.

There are many types of caching mechanisms like memcached, APC, eAccelerator but for the simplicity of this tip, we will use plain file to hold our cache data. This is enough in most of cases.

So let’s see how our caching class looks like:

[code lang=”php”]
/**
* @desc Class that implements the Cache functionality
*/
class Cache {

/**
* @desc Function read retrieves value from cache
* @param $fileName – name of the cache file
* Usage: Cache::read(‘fileName.extension’)
*/
function read($fileName) {
$fileName = ‘/path/to/cache/folder’.$fileName;
if (file_exists($fileName)) {
$handle = fopen($fileName, ‘rb’);
$variable = fread($handle, filesize($fileName));
fclose($handle);
return unserialize($variable);
} else {
return null;
}
}

/**
* @desc Function for writing key => value to cache
* @param $fileName – name of the cache file (key)
* @param $variable – value
* Usage: Cache::write(‘fileName.extension’, value)
*/
function write($fileName,$variable) {
$fileName = ‘/path/to/cache/folder’.$fileName;
$handle = fopen($fileName, ‘a’);
fwrite($handle, serialize($variable));
fclose($handle);
}

/**
* @desc Function for deleteing cache file
* @param $fileName – name of the cache file (key)
* Usage: Cache::delete(‘fileName.extension’)
*/
function delete($fileName) {
$fileName = ‘/path/to/cache/folder’.$fileName;
@unlink($fileName);
}

}
[/code]

Save above code as cache.php. We’ll use it later.

Code is well commented so I will not explain the details. Notice that in function write we use function serialize and in read unserialize . As PHP manual says:

Serialize generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

So we are just adjusting PHP value in more “storable” way.

Here is how you can use this in your application:

[code lang=”php”]
// include the class
require_once(‘cache.php’);
//instantiate it
$cache = new Cache();
//let’s check if some cache file exists
$data = $cache->read(‘test_17.tmp’); //17 is id of the article, for example
// it doesn’t exist, fetch data from database
if (empty($data)) {
$sql = “SELECT image, user_id, content FROM table WHERE id = 17”;
$data = $db->select_list($sql); // just an example
$cache->write(‘test_17.tmp’, $data);
}
// then use the data as you would normally
foreach($data as $row) {
……..
}
[/code]

This way you will gain some speed and your database server will thank you. But there is a catch! It is very, very important not to forget to clear this cache if something gets changed on that particular article. So do not forget to add this lines after your update the article:

[code lang=”php”]
// include the class
require_once(‘cache.php’);
//instantiate it
$cache = new Cache();
//updating the article example
$data = ‘some array for updating’;
$db->update_record(‘table’, $data);
$cache->delete(‘test_17.tmp’);
[/code]

Now you clear the cache and the new version of the article will appear, and the new Cache file will be created.

]]>
https://www.codeforest.net/cache-for-your-database-queries/feed 4