I am trying to make my own CMS and I am pretty new in php and mysql. Let me get to the point:
So far I've created news in index page with "read more" permalinks (which means, when I press read more, it moves me to other page e.g. /readmore.php?id=[news ID]
and in that page the only content is those specific news i.e specific row from table. What I'm stuck with is getting that specific row ID in that permalink.
Let me show the code that currently works for me.
index file with news:
while($row = mysql_fetch_array($result))
{
/*... title, news content... */
echo "<a href='readmore.php?id=".$row['ID']."'>".$read_more_link."</a></div>";
}
readmore.php with exact row (for example readmore.php?id=1201) :
$params = $_SERVER['QUERY_STRING'];
$str = $params;
$id1 = $str[strlen($str)-1];
$id2 = $str[strlen($str)-2];
$id3 = $str[strlen($str)-3];
$id4 = $str[strlen($str)-4];
$news_id = "$id4$id3$id2$id1";
$query = "SELECT * FROM naujiena WHERE ID='$news_id'";
Basically what it does, it recovers 4 last digits from address bar and searches for those news with that 4 digit ID
It's a very primitive way of doing this, but I'm stuck with this for a few days and can't find a way out.
What I've tried before, is to create a variable with session in the while($row = mysql_fetch_array($result))
loop, it shows IDs in the index page as it should, but in readmore page only the last one or the first one (depends on desc or asc) which was quite obvious to expect
Can you help me? I would appreciate it.
You can access the values in the query string by name in the $_GET
array.
For example, $_GET['id']
will be the value of the id=<ID>
part of the query string. It works for every field of the query string.
// url : readmore.php?id=1201
$news_id = intval($_GET['id']);
// now, $news_id contains the value 1201
$query = "SELECT * FROM naujiena WHERE ID='$news_id'";
You can read the official help : $_GET
or one of the various tutorial you can find on the web : http://www.w3schools.com/php/php_get.asp
Update
Since you accepted my answer, I feel obligated to also throw a word about SQL injection. You should always sanitize any input you're using in a SQL query with mysql_real_escape_string
. You can find more details on Wikipedia : SQL injection or in the PHP documentation : SQL Injection.
Since your IDs are numeric values, you can also ensure that. I updated the code snippet to do this with intval
.