how to create link depending on user input - php

This is the code for the user to post the post.
if(islet($_POST['submit'])) {
$name = $_POST['name'];
$keywords = $_POST['keywords'];
$description = $_POST['description'];
if(islet($_GET['user_id'])) {
$_SESSION['user_id'] = $_GET['user_id'];
} //Then I just have a inset into statement for my database with these 4 variables.
}
I have a web form that creates a post by the user. I now want to make the user able to go back to a page dedicated to that post for them to edit, add on to etc.

Here is the high level solution:
You need to create a page that expects a post_id as a parameter of the query string. That page will be accessed like this: http://yoursite.com/show-post.php?post_id=136
In PHP, retrieve that post_id: $_GET['post_id']
From that post id, pull from the DB the information associated to that id. Something like SELECT * FROM post WHERE post_id = $_GET['post_id'].
Then display the post using the information returned by the SQL query.
If you want to show a list of posts from the current user, create another page http://yoursite.com/my-posts.php.
From that page, write a SQL query based on the current user id: SELECT * FROM post WHERE user_id = $_SESSION['user_id'] (assuming you have a user_id in the post table, and the user has authenticated and his id was stored in the session).
That will fetch you a list of posts, loop through them to get their details.
Please note that you should escape the parameter passed in the query string. There are many ways to do this so I won't go into it here.
EDIT:
This is how you generate the links:
<?php foreach ($mysql_result as $row) { ?>
link
<?php } ?>
Then, in edit-post.php, you can get the post_id by doing $postId = $_GET['post_id'];, and then use it in the query to fetch ALL the information about that one particular post.

Make sure you have a unique ID column in your database - call it 'postid', and set it to autoincrement with every new entry.
That way you'll be sure to have a unique identifier for each entry you insert in to the database.
You then need to retrieve a list of items in the database, including the postid, and for each row in the database provide a link to display it.
If a postid is selected in the url, then display information for that post. If it isn't, then show a list:
<?
$dbh = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
///No post id selected, display a list of everything
if(!$_GET['postid']) {
print "You're listing all the rows in the database<br/>";
$query = $dbh->prepare("SELECT `postid`,`name` FROM `table` ORDER by postid ASC");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
print "".$row['name']."<br/>";
}
} else { //A post ID is selected
$postid = $_GET['postid'];
Print "Select from the database where postid = ".$postid;
$query = $dbh->prepare("SELECT `postid`, `name`, `keywords`, `description` FROM `table` WHERE `postid` = '$postid' LIMIT 1");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$name = $row['name'];
$keywords = $row['keywords'];
$description = $row['description'];
print 'Displaying details for '.$name.': '.$keywords.', '.$description.' - create edit links here... <br/><br/>';
}
} //End post id is selected
?>

Related

How to get top most liked post among my all post from mysql using PHP

As per the below code status='notlove' shows that the user already liked, and status='love' indicated that user liked it and again unlike this post,
The Qus is, the code gives me the proper result but when i liked a new post,
it is not showing me the proper result, instead of showing most liked post it is showing me the New Post result, How can i solve this Issue?
Kindly refer my Table View also
I'm getting the user which is logged in
$id = $_SESSION["id"];
//query for getting the top most timeline id of current log in user
$sql= "SELECT *
FROM lovetimeline
INNER JOIN (
SELECT userId, MAX(timelineId) AS Maxscore
FROM lovetimeline
GROUP BY userId
) topscore
ON lovetimeline.ownerId = '$id'
AND status='notlove'
AND lovetimeline.timelineId = topscore.maxscore";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
//getting the top liked post from table
$_SESSION["toppost"] = $row["timelineId"];
}

How to get data for specific post id?

I'm using wordpress for building a site.
I have in the database a column with the id of the post and I want to use a template for all posts to get the data.
What I want to do is: if post id is the same as in the database column get the data and show it.
I'm using a sql query now, but it shows the data of all posts. How can I get the data for the specific post?
The database look like this:
column: wordpress_id = 275 | name = example1
column: wordpress_id = 285 | name = example2
275 and 285 is the id of the post in wordpress. if i say
$sql = "SELECT * FROM tablename WHERE wordpress_id=275";
in the template, it doesn't show the data of post id 285.
Read this documentation: https://developer.wordpress.org/reference/functions/get_post/
In WordPress, your posts and custom post types are stored in same table and it is not required to specify the post type. So you can use the following code to fetch post from the database using id.
$id = YOUR_POST_ID;
$post = get_post( $id );
Check the output and grab values which is needed.
Note: If you are using hooks available in WordPress, there is methods to get data from database without using normal MySQL queries.
I hope this helps.
I found a solution:
<?php
$id = get_the_ID();
$sql = "SELECT * FROM example WHERE wordpress_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Example: " . $row["example1"]. "<br>";
}
mysqli_close($con);
?>

Show data from a specific row in MySQL

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=?";

PDO getting values

I made a blog. Everything is working correctly except for one thing; being able to compare my id in order to open the appropriate article.
I'm using FETCH_ASSOC:
$sth->setFetchMode(PDO::FETCH_ASSOC);
I'm checking $_GET for an id:
if (isset($_GET['id']) && ($_GET['id'] == $blogid['id'])) { **PROBLEM IS WITH $blogid
$row = $sth->fetch()
//... Code to display html and db values
If true, it shows the entire blog post. Else it displays all the blog intros:
<?php } else { ?>
<?php while($row = $sth->fetch()) { ?>
//... Code to display html and db values
How can I access the id in my if statement? If I do something like:
$blogid = $sth->fetch()
it screws up $row = $sth->fetch() by reordering the posts
EDIT Query added:
$sth = $dbh->query('SELECT id, title, slug, body, image, author, date, category from blog ORDER BY date DESC');
You're using PDO and MySQL slightly wrong here. Instead of getting all the blog posts and checking to see whether the one you've got has the correct ID, you should only get one blog post (row) from the DB using a WHERE clause, like this:
SELECT id, title, ... FROM blog
WHERE id=[ID from $_GET]
ORDER BY date DESC
PDO handles this for you fantastically well by allowing you to use placeholders:
SELECT id, title, ... FROM blog
WHERE id=:theBlogID
ORDER BY date DESC
Here, I've used the placeholder :theBlogID which will be replaced by the $_GET parameter .
Using PDO, your final code needs to prepare the query, bind a parameter to it, execute it and then get the result (checking if there actually is a result using PDO::rowCount()) something like this:
$sth = $dbh->prepare('SELECT id, title, ... FROM blog
WHERE id=:theBlogID
ORDER BY date DESC');
$sth->bindParam(':theBlogID', $_GET['id'], PDO::PARAM_INT); // Bind the ID from $_GET to the placeholder
$result = $sth->execute(); // Execute (run) the query
if($result->rowCount()) { // Have we found any blog posts with the ID specified?
$data = $result->fetchAll();
foreach($data as $post) {
// Print out your blog post
}
}
It's not clear how much of the above you currently have as you only give one or two line snippets here and there, but this should give a good outline of what you need to do.

Building a dynamic HTML list from MySQL results

I have a set of tables (for this question I'll say two) in the database, one of which is the users table and one of which is one for storing URL's. The one that store URL's contains the URL ID (auto increment) and the User_ID. The user id is submitted when the add url form is submitted.
I'm trying to figure out how I can display these results as a table. For each user I need to get the list of URL's that are associated with their account and display them as a list. I have the user-id stored as a variable so it can be called from anywhere. How would I select items from the database that are only associated with the current logged in users id? and also how would I then generate a list of the results.
Thanks in advance.
This is a very basic php mysql question so you can probably find it by looking around the site but to save you some time:
//assuming the userid for logged in user is in $userid
$sql = "SELECT * FROM urls_table WHERE User_ID=$userid";
$result = mysql_query($sql); $data = array();
while($row=mysql_fetch_assoc($result)) {
$data[] = $row['URL'];
}
print_r($data);
//or foreach($data as $url) print "$url\n";
If instead of the user id of the logged in user you had the name then do an inner join like so:
//assuming the user name for logged in user is in $username
$sql = "SELECT * FROM urls_table INNER JOIN users_table ON urls_table.User_ID = users_table.User_ID WHERE User_Name=$username";
$result = mysql_query($sql); $data = array();
while($row=mysql_fetch_assoc($result)) {
$data[] = $row['URL'];
}
print_r($data);
//or foreach($data as $url) print "$url\n";

Categories