How to get data for specific post id? - php

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);
?>

Related

add one (+1) to a field in mysql database using php

I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.

how to create link depending on user input

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
?>

Add link to mysql row result which points to the same result

Hello my data base have various columns , in a mysql fetch I am listing only the title column, but I would like that list to make a link on the already listd result which link will open a new page with the same result but this time listing all the columns from the table on this row.
mt SQL fethc is:
(!$result = mysqli_query($con,"SELECT * FROM tablename WHERE type = 'Panes'"))
and my sql result is: <?php echo $row['name']; ?> -> which result I would like to be link.
I wold like to know if somebody have any suggestion for a possible resolution. Thanks!
You cannot do that if you want to have a single query in your code(base from your query).
You must do another query for the click item or link..
If you do not need all the columns in your table to not use * instead select only what you need to make your code more readable and to be faster to execute.
Revised your string query,
"SELECT id, name FROM tablename WHERE type = 'Panes'"
and in your code to display the result to make a link,
<?php echo $row['name']; ?>
And in your page displayAllColumns.php you must get the passed data through get method
$id = $_POST['id'];
//then make a query for that to select all the data on that id
//just have to type only the string so
"SELECT * FROM tablename WHERE id = '$id'"
//you must use `*` because you need to display all the columns then write your table code to display the result.
Hope it helps
Try echoing an anchor tag. $row['name']
Use something like this:
<?php echo $row['name']; ?>
The display_item.php script then displays the row with the ID in $_GET['id'].

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

Need help for a specific MySQL query used in a PHP loop

The main code which i use is
while ($row = mysql_fetch_assoc($result1)) {
echo $row["user_id"];
$new = "[grade uid=\"{$row["user_id"]}\" value=\"{$groupgrade}\" format=\"{$groupformat}\" prv_comment=\"{$groupprivatecomment}\" pub_comment=\"{$grouppubliccomment}\"] ";
$sqq = "UPDATE wp_postmeta SET meta_value='$new' WHERE meta_key='grade' AND post_id= $post_id ";
$result = mysql_query($sqq);
echo "grade has been updated";
}
Which affects the rows in table wp_postmeta as shown in the picture on the link Where all the variables undefined here are defined before this para .
What i actually want that user id must be different in different rows.
The only thing happening in this loop is that each uid from the array gets written in all the rows one after the other and only the last uid persists finally which is 3 in the diagram but i only want that each uid should come separately i.e., differnt uid for diff. meta_id . Please help
REGARDING CODE
$result1 fetches an array of userids from a defined mysql function and rest variables are user defined.
I am kinda new to php and to programming so please help
The question is not very clear and it's WordPress related and you didn't add WordPress tag in your question. Anyways, WordPress has it's own function to handle post meta. In your loop you are trying to update post meta manually but it's possible to do that using WordPress' update_post_meta function. The syntax is given bellow
<?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>
In this case you can use following code
<?php update_post_meta($post_id, 'grade', $new); ?>
Here $post_id will be your post id which you want to update.
OK, now that I understand your problem (you confused me by saying that "all rows" were being updated, you just mean all rows with this post_id), I think this is the answer:
$sql2 = "SELECT meta_id FROM wp_postmeta where meta_key='grade' AND post_id = $post_id";
$result2 = mysql_query($sql2);
while (($row = mysql_fetch_assoc($result1)) && ($row2 = mysql_fetch_assoc($result2))) {
echo $row2["meta_id"], ' => ', $row["user_id"];
$new = "[grade uid=\"{$row["user_id"]}\" value=\"{$groupgrade}\" format=\"{$groupformat}\" prv_comment=\"{$groupprivatecomment}\" pub_comment=\"{$grouppubliccomment}\"] ";
$sqq = "UPDATE wp_postmeta SET meta_value='$new' WHERE meta_key='grade' AND post_id= $post_id AND meta_id = {$row2["meta_id"]}";
$result = mysql_query($sqq);
echo " grade has been updated";
}
The new $sql2 query gets each meta_id, and updates each row with a different user_id from $result11.
your code is to work around this $row["user_id"]
if it same user who posted then the result will be true 3
if this variable is from other query then u must look to this query how u getting this user_id or , publish it in your question , to see why it comes only 3.
its better to make a column for user_id to insert data specialy for that user.
$row["user_id"] is beeing a warning variable to sql injection , so it must be escaped by mysql_real_escape_string()

Categories