PDA

View Full Version : Returning db data based on url, help


Kineas
11-06-2009, 08:10 PM
I've made an RSS feed for my blog, and when I click on the title of a blog, I want it to take the user to a page to view that blog entry. Anyway, I've done this by having the blog id in the hyperlink, so when clicking on the link, it takes you to www.abc.com/blog.php?blog=1. The mysql database containing my blog entries has id, title, and message. So far, I've got this:

$dbServer=@mysql_connect("localhost","","");
if (!$dbServer) {echo "Failed to connect to MySQL"; exit; }

mysql_select_db("");

if($_GET['blog']){

$sql ="SELECT * FROM messages";
$sql.=" WHERE id LIKE '%".mysql_real_escape_string($_GET["blog"])."%'";

$queryResult=mysql_query($sql);

echo $dbRecord['title'];

}else
{
}


I'm not sure if my syntax is right to get the data from the database as nothing is showing when this is run. Any help with this would be great, thanks.

Coyote6
11-06-2009, 08:35 PM
SELECT * FROM messages WHERE id=inputted_id;


If all your ids are numbers then use this and make sure you fetch your record from the database.

if ((isset ($_GET['blog'])) && (preg_match('|[0-9]+|', $_GET['blog']))){

// No longer really necessary as only numbers are allowed. Could just use $id = $_GET['blog'];
$id = mysql_real_escape_string($_GET['blog']);

$sql ="SELECT * FROM messages WHERE id=$id";
$queryResult=mysql_query($sql);
if (mysql_num_rows($queryResult) == 1) {
$dbRecord = mysql_fetch_assoc ($queryResult);
echo $dbRecord['title'];
}

}

Kineas
11-06-2009, 11:15 PM
Thanks a lot, works perfectly.

bazz
11-07-2009, 01:34 AM
Good that you got your data but it is better not to use select * in a finished script.

If you ever change your db colsaround or add new ones, that * usage will bring in data that you don't need and would therefore be inefficient.

The second reason is that after the addition of more cols, the script may return data in the wrong order/format and could therefore break your script, especially if the 'new' cols are amongst existing ones.

Almost always select the data you need by column(s).


select title
, message
from the_table
where id = 'something'
etc

I've used the word 'something' because I don't know php syntax. (I use perl).

bazz

Coyote6
11-07-2009, 06:34 AM
Very true. Try not to use * at all.

Also change

preg_match('|[0-9]+|', $_GET['blog'])

// To
preg_match('|^[0-9]+$|', $_GET['blog'])


Mistake on my part.