Jump to content

Basic problem with fetching sql data


MrLoefjo

Recommended Posts

Heya.

 

I have a very basic problem.

 

I am following some tutorials to create a Blog, but im changing it around a bit, to fit it better to my needs. Atm i have a small database, one of the tables in it is blog, which has id, title, entry and date section.

 

Problem lies in following code:

<?php
require("config.php");

if(isset($_GET['id']) == TRUE) {
if(is_numeric($_GET['id']) == FALSE) {
$error = 1;
}
if($error == 1) {
header("Location: " . $config_basedir);
}
else {
$validentry = $_GET['id'];
}
}
else {
$validentry = 0;
}

require("header.php");

if($validentry == 0) {
$sql = "SELECT blog.* FROM blog ".
"ORDER BY Date DESC ".
"LIMIT 1;";
}
else {
    echo "$validentry";
$sql = "SELECT blog.* FROM blog ".
"WHERE blog.id = " . $validentry .
"ORDER BY Date ASC ".
"LIMIT 1;";
}

$result = mysql_query($sql);

$row = mysql_fetch_assoc($result);

 

 

specifically, this line : "WHERE blog.id = " . $validentry . isn't working. When i add it, i get fetching error in last line, when i remove it works fine. I made sure, that validentry is ok, using the echo. Also inserting SQL command in phpmyadmin: " SELECT blog.* from blog WHERE blog.id = 1, or 2 works fine.

 

Any help would be appreciated.

 

MOD EDIT: code tags added.

Link to comment
https://forums.phpfreaks.com/topic/240030-basic-problem-with-fetching-sql-data/
Share on other sites

There's no need to do all of the string concatenation you're doing; it just leads to problems like the one you're having. If you echo the query, you'll see there is no space between the $validentry variable and ORDER BY. You should also incorporate some basic logic to check for and handle errors such as these.

 

$sql = "SELECT blog.* FROM blog ".
"WHERE blog.id = " . $validentry .
"ORDER BY Date ASC ".
"LIMIT 1;";

// Would be better written as:
$sql = "SELECT blog.* FROM blog WHERE blog.id = $validentry ORDER BY Date ASC LIMIT 1";

Variables are interpolated within a double-quoted string, so concatenation isn't needed.

 

Both of these are perfectly valid, but the one without the concatenation is much easier to read, and a lot less likely to contain typos.

$query = "SELECT `$field` FROM `$table` WHERE `$field` = '$value' ORDER BY `{$array['index']}` DESC";
// versus //
$query = "SELECT `" . $field . "` FROM `" . $table . "` WHERE `" . $field . "` = '" . $value . "' ORDER BY `" . $array['index'] . "` DESC";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.