On today's tutorial we will talk about creating a blog on php and mysqlTable of contest:1. Connecting to mysql database2. Creating mysql tables3. Coding the blog Download Connecting to mysql database is simple, in just few lines of codeBefore we start i suggest you read Php Mysql posting to database for better understanding of mysql.// connecting to host
mysql_connect("host", "user", "password"); // replace this with your data
mysql_select_db("your_database"); // database name here
?>Creating database, tables and columns Now let's build the mysql table.First build a database if you haven't, and dont forget to edit the connection details at the top.Click on databasesSet a name to it and click create.
Now we must build the tables:
Click 'go', a new table will popup, complete those fields like in the pocture below:
Scroll down and click save.
Last one, click on posts and insert tab at top, write something to title, and id live empty.
Now lets continue coding the blog
// connecting to host
mysql_connect("host", "user", "password"); // replace this with your data
mysql_select_db("your_database"); // database name here
// lets build a blog
if(isset($_GET['post'])){
$post = $_GET['post'];
// first of all we will check string length
if(strlen($post) > 11){ // if post id is bigger than 11 charachters
die('Blog post nof found.');
}
// now we will make sure that the post id is numeric and this is a nice security method
if(is_numeric($post)){ // is numeric allows numbers only
$post = (int)$post; // and the int function, which replace every
// string to its correspoing number
// for the tutorial im gonna add mysql_real_escape_string
// but is not really needed in this case
$post = mysql_real_escape_string($post); // final sqli defense
// final part
$query = mysql_query("SELECT title FROM posts WHERE id=$post LIMIT 1");
while($row = mysql_fetch_array($query)){
echo $row['title'];
}
}
else{ // if post is not numeric then
die('Blog post nof found.'); // post does not exist
}
}
else{
// if post is not submitted display them all
$query = mysql_query("SELECT title, id FROM posts");
while($row = mysql_fetch_array($query)){
echo $row['title'];
echo $row['id'];
echo ''.$title.'
';
}
}
?>Few last tips!I used LIMIT 1 on the first mysql query.That's done for 2 main pruposes:1. we are only displaying 1 result2. it's a nice speed optinization for mysqlTo display blog posts by newest ones replaceSELECT title, id FROM postswith SELECT title, id FROM posts ORDER BY id DESCIt's a simple blog who does the work.If you want to learn more about sql injection we suggest Sql Injection prevention tutorial
We appreciate you for reading our post, but we think it will be better you like our facebook fanpage and also follow us on twitter below.
Title :
Php Mysql blog tutorial, creating a simple and secured blog
Description : On today's tutorial we will talk about creating a blog on php and mysql Table of contest: 1. Connecting to mysql database 2. Creating ...
Rating :
5