I'm developing a news website with php-mysql.
This is the table:
news_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
news_title VARCHAR(250) NOT NULL,
news_short_description TEXT NOT NULL,
news_full_content TEXT NOT NULL,
news_author VARCHAR(30) NOT NULL,
news_published_on DATE NOT NULL
)";
on the index page of the website will be shown the articles.
$sql = "SELECT news_id,news_title,news_short_description,news_full_content,news_author,news_published_on FROM ARTICOLI ORDER BY news_id DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h3>". $row["news_title"]. " </h3><br> " . $row["news_short_description"]. "<br> " ."Posted by ". $row["news_author"]. "<br>";
}
} else {
echo "0 results";
}
WHAT I NEED?
i don't know how to create automatic pages and links for the single articles.
EXAMPLE: www.website.com/this-is-the-title-of-the-article.
i was thinking about using the id of the db table,but how to select one precise row?
can you help me? thanks!!! ;)
One idea.
First of all, you need to add a slug field in your table (https://en.wikipedia.org/wiki/Semantic_URL#Slug) which will hold the title in the form of this-is-the-title-of-the-article.
The assumption here would be that the "slug" will need to be a unique string in the table.
Secondly, you need to use some sort of rewrite mechanism (e.g. apache's mod_rewrite) to convert request of the form www.website.com/this-is-the-title-of-the-article to something you can handle via a PHP script.
For example www.website.com/this-is-the-title-of-the-article gets rewritten as as www.website.com/index.php?q=this-is-the-title-of-the-article).
Example .htaccess
RewriteRule ^(.*)$ /index.php?q=$1 [L]
index.php
<?php
$articleSlug = isset($_GET(["q"])?$_GET["q"]:null;
if ($articleSlug !== null) {
$query = "SELECT news_id,news_title,news_short_description,news_full_content,news_author,news_published_on FROM ARTICOLI WHERE slug=?"; // Bind the ? to $articleSlug
//Execute SQL here and echo the results
} else {
// 404 error
}
I understand this is a very vague description and this is only one way of doing it. I would personally suggest you look into an MVC framework like e.g. Laravel which has all of this functionality already built in.
Related
Good afternoon all,
I'm in the finishing stages of making a website where users can register and login. After that they can upload documents such as .pdf and .docx and search for those documents. The users data gets stored in my users table which contains following:
idUsers int(11) PRIMARY KEY NOT NULL,
uidUsers TINYTEXT NOT NULL,
emailUsers TINYTEXT NOT NULL,
pwdUsers LONGTEXT NOT NULL,
Then I have a table called "files" where the files that are being uploaded by the user i stored. The table contains following:
id int(11) PRIMARY KEY NOT NULL,
usersId int(11) NOT NULL, - (Foreign key for idUsers in users table)
name varchar(255) NOT NULL,
title varchar(255) NOT NULL,
forfatter varchar(255) NOT NULL, (forfatter = author)
size int(11),
download int(11) (for later use)
So when a specific user are logged in and uploads document, the users "id" (primary key in users table) gets passed to "usersId" in my files table.
All of this is working perfectly fine so far.
Then the user are able to use a search function, where the user can search for name, title and author of the document, which also works fine.
I only need to make sure the user only can see the documents, that are being uploaded by themselves. But I can't figure it out. I've tried many different solutions so far.
I've tried a suggestion i saw, where i tried to make my mysqli_query look like this:
"
SELECT *
FROM files
WHERE id
AND usersId name LIKE '%$searchingq%'
OR title LIKE '%$searchingq%'
OR forfatter LIKE '%$searchingq%'
AND usersId='.$usersId.'"
That wasn't working out well. It felt like the sessions wasn't finding the id of the current $_SESSION.
My search .php looks like this:
$usersId = $_SESSION['userId'];
$output = '';
if (isset($_GET['search']) && $_GET['search'] !== ' ') {
$searchingq = $_GET['search'];
$q = mysqli_query($conn, "SELECT * FROM files WHERE `usersId` = {$usersId} AND (`name` LIKE '%{$searchingq}%' OR `title` LIKE '%{$searchingq}%' OR `forfatter` LIKE '%{$searchingq}% )");
$c = mysqli_num_rows($q);
if($c == 0) {
$output = '<p>No search results for: "' .$searchingq. '"</p>';
} else {
while($row = mysqli_fetch_array($q)) {
$name = $row['name'];
$title = $row['title'];
$forfatter = $row['forfatter'];
$download = $row['downloads'];
$output .=
Help is very appreciated!
When doing code like this, I like to first run the query itself just to get it right.
This type of filtering should be easy because you already have each file associated to a user.
The base query would be like this:
Assuming you are looking for files for user 99.
This is the basic query and is intended only to show how to get the files for a user. This does not go into the code.
SELECT * FROM files
WHERE `usersId` = 99
This would give you only files that belong to that user. Again, this is only to explain the query, not to go in the code.
Now let's add to the above query to include the search criteria. Assume we are looking for 'foo'
SELECT * FROM files
WHERE `usersId` = 99
AND (`name` LIKE '%foo%'
OR `title` LIKE '%foo%'
OR `forfatter` LIKE '%foo%' )
We now have a query we can use in code. Try this out by running it directly against your database.
This query says to find all the files for that user when any of the columns match the search criteria. You can, therefore, write this in PHP something like this:
(Some code has been removed for the sake of brevity)
$usersId = $_SESSION['userId']; // the user id of the logged in user.
// code removed
$searchingq = $_GET['search']; // the search string
$q = mysqli_query($conn, "
SELECT * FROM files
WHERE `usersId` = {$usersId}
AND (`name` LIKE '%{$searchingq}%'
OR `title` LIKE '%{$searchingq}%'
OR `forfatter` LIKE '%{$searchingq}% )";
while($row = mysqli_fetch_array($q)) {
// Do output here
}
The following is how to do it with prepared statements.
You can learn more about Prepared Statements here: https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
$stmt = $mysqli_prepare($conn, "
SELECT * FROM files
WHERE `usersId` = ?
AND (`name` LIKE '%?%'
OR `title` LIKE '%?%'
OR `forfatter` LIKE '%?% )");
// Replace the ?'s with the actual values.
mysqli_stmt_bind_param($stmt, "isss", $usersId, $searchingq, $searchingq, $searchingq);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
// output goes here
}
Maybe you could try adding AND usersId=".$userId to the end of your query.
How exactly do I subtract values from a database using php? I see plenty of examples using static variables such as
<?php
$first_number = 10;
$second_number = 2;
$third_number = 3;
$sum_total = $third_number + $second_number * $first_number;
print ($sum_total);
?>
However I'm looking to subtract one database value from another, then multiply that value by another db value. To give some more detail, I have an inventory database where I'm echoing the values into a table, I'm attempting to subtract the total quantity of an item from the minimum quantity, to see how many need to be ordered, then multiply the number of parts we need to order by the cost of that part. I've dug around and found a few possible methods such as
$query = "SELECT `db`,
(`minimumquantity` - `totalquantity`) AS `quantitytoorder`
FROM `db`
WHERE id ='".$id."';"
and
<?php
$minimumquantity = $_GET['minimumquantity'];
$totalquantity = $_GET['totalquantity'];
$quantitytoorder = $minimumquantity - $totalquantity;
print ($quantitytoorder);
?>
Please before you laugh, I'm very much a beginner, can anyone point me in the right direction, or provide me with proper examples? My only real resource is the net and most examples I find are very high-level.
Field Type Null Key Default Extra
id int(3) NO PRI NULL auto_increment
partnumber varchar(20) NO NULL
description varchar(20) NO NULL
tonerprice int(20) NO NULL
totalquantity int(20) NO NULL
minimumquantity int(20) NO NULL
quantitytoorder int(20) NO NULL
replencost int(20) NO NULL
So assuming you know how to work with SQL in PHP, it's as simple as this:
// STOP USING mysql, use mysqli or PDO, for demonstration purposes only
$results = mysql_query('SELECT foo, bar, baz FROM table');
while ($row = mysql_fetch_assoc($results)) {
echo $row['foo'] - $row['bar'] * $row['baz'];
}
Assuming the columns are all numeric, that's all you need to do to subtract and multiply values from the database in PHP.
Firstly you will need to look into using mysql within php. Php has a built in class specifically created to do this. Documentation, examples and everything else a beginner needs is available here.
Secondly the query you are trying to do is possible and you are on the right tracks, try something like this:
$query = "SELECT (minimumquantity - totalquantity) AS quantitytoorder, (quantitytoorder * costofpart) AS totalcost FROM db WHERE id = '".$id."';";
My advice is to read through the mysqli documentation and do some simple examples first to get familiar with it - then you should try and complete your own task.
Try this query
SELECT (value2-value1) as minimumquantity,((value1 + value2)* value3)
as totalquantity FROM table WHERE id = '".$id."';";
I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";
Hey guys sorry if this is an amateur question but I'm having a little trouble with this.
How do I display comments towards a specific page? (page.php?id=48)
Because right now, every time i post a comment, it displays on all pages instead of the one i wanted it to post on
Heres the code:
$userfinal=$_SESSION['username'];
$rs = mysql_query("SELECT id FROM searchengine") or die(mysql_error());
$rec = mysql_fetch_assoc($rs);
$id = $rec['id'];
// get the messages from the table.
$get_messages = mysql_query("SELECT messages_id FROM messages WHERE to_user='$id' ORDER BY messages_id DESC") or die(mysql_error());
$get_messages2 = mysql_query("SELECT * FROM messages WHERE to_user='$id' ORDER BY messages_id DESC") or die(mysql_error());
$num_messages = mysql_num_rows($get_messages);
// display each message title, with a link to their content
echo '<ul>';
for($count = 1; $count <= $num_messages; $count++){
$row = mysql_fetch_array($get_messages2);
// if the message is not read, show "(new)"
// after the title, else, just show the title.
if($row['message_read'] == 0)
Any help would be appreciated, thanks
take a look at my sample code.
Consider a table comments with the basic structure.
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`comment` text NOT NULL,
`article_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
comment column will hold the text of your comment
article_id holds the foreign key of the article it belongs to.
now lets say you want to retrieve the comment from a particular articleid article.php?id=48
here is how you should be doing it.
$articleId = mysql_real_escape_string($_GET['id']);
$query = 'SELECT id,comment FROM comments WHERE article_id ='.$articleId;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo nl2br($row['comments']);
}
although my codes does not relate to your question at all, but it should give you the basic idea on how to implement the logic.
EDIT :
you should not use the code for production, the code is only meant to explain you to implement the logic, remember this code is vulnerable to SQL injections, if you want a temporary fix you could use mysql_real_escape_string() function to avoid it. check my updated code.
TIP : you should try and use PDO for all your database queries here is the tutorial to get you started http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the SQL for 'next' and 'previous' in a table?
I'm trying to find a better way to get the next or previous record from a table. Let's say I have a blog or news table:
CREATE TABLE news (
news_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
news_datestamp DATETIME NOT NULL,
news_author VARCHAR(100) NOT NULL,
news_title VARCHAR(100) NOT NULL,
news_text MEDIUMTEXT NOT NULL
);
Now on the frontend I want navigation buttons for the next or previous records, if i'm sorting by news_id, I can do something rather simple like:
SELECT MIN(news_id) AS next_news_id FROM news WHERE news_id > '$old_news_id' LIMIT 1
SELECT MAX(news_id) AS prev_news_id FROM news WHERE news_id < '$old_news_id' LIMIT 1
But the news can be sorted by any field, and I don't necessarily know which field is sorted on, so this won't work if the user sorts on news_author for example.
I've resorted to the rather ugly and inefficient method of sorting the entire table and looping through all records until I find the record I need.
$res = mysql_query("SELECT news_id FROM news ORDER BY `$sort_column` $sort_way");
$found = $prev = $next = 0;
while(list($id) = mysql_fetch_row($res)) {
if($found) {
$next = $id;
break;
}
if($id == $old_news_id) {
$found = true;
continue;
}
$prev = $id;
}
There's got to be a better way.
Edit, clarifications:
Why dont I use limit? I would need to know the position in the result set of the current record, which I don't. If this were your typical pagination, and I had query strings like ?startpage=n then yes that would work, I could just increment $startpage and add LIMIT $startpage,1 to the query. But I have urls like news/news_id-news-title-here that are rewritten to ?news_id=n, so I don't know what the startpage is. Even if I did, what if the user gets there via an external link? What if new posts are added while the user is reading the current page?
Don't get too stuck on the specifics of the example above, the real question is this:
Given a unique record id and an arbitrary sort column, is there a way to determine which records fall immediately before and after that specific record, without looping through the entire record set.
why don't you use the same way for the news_author you used for the news_id?
EDIT:
There is one pitfall: news_author is not unique for sure. So, you will need to order news_author query by 2 fields : news_author, news_id. So, you will need 2 conditions to get next author
Why you dont use limit ?
e.g. you listing 10 items per page. Limit 1,10
the next 10 items: Limit 11,10
and so on.
no matter if you display one or 100 items per page, the system is always the same.
EDIT: more explanation needed, if you have a detail page, you most certainly will come to it via a list, the list was created with a certain query, so you know the position in this list, and can give this param to the detail page. so when you there have prev/next links you can call the query with a limit of 1 and the offset from your params.
EDIT 2: You can use a query to find the position of the row based on your order but this will only work with DESC:
SELECT COUNT(*)+1 FROM news ma JOIN news mp ON (mp.$sort_column, mp.news_id) > (ma.$sort_column, ma.news_id) WHERE ma.news_id = $news_id;
in pseudo code:
$currentValue = "SELECT $sort_column FROM news WHERE news_id = $current_news_id LIMIT 1"
$operator = ($sort_way == 'ASC')?' > ':' < ';
$nextNewsId = "SELECT news_id FROM news WHERE $sort_column $operator $currentValue ORDER BY $sort_column $sort_way LIMIT 1"
no?