Generate new post WordPress based on MySQL database - php

I have created a Wordpress page to show dynamic content based on MySQL database. The content will be shown based on the URL parameter.
Ex: https://domainname.com/hotel-details/?hotelcode=First-Hotel
Is it possible to generate a new post for each database row?
So, instead of using an URL parameter like one above, the URL could be: https://domainname.com/hotel-details/First-Hotel
I created this dynamic page by inserting a PHP code to a Wordpress page (I use Advanced Ads plugin to insert the code)
<?php
if (isset($_GET['hotelcode']))
{
$hotelcode = $_GET['hotelcode'];
}
else
{
$hotelcode = "";
}
include 'dbconnect.php'; // MySQL DB connection
$dbconnect = mysqli_connect($host, $user, $password, $database);
$dbresult = mysqli_query($dbconnect, "
SELECT *
FROM HotelDatabase
WHERE HotelSlug='$hotelcode'
");
foreach ($dbresult as $row);
$HotelName= $row['HotelName']; $HotelDetail= $row['HotelDetail'];
$Image= $row['Image']; $Review= $row['Review'];
?>
<?php if($dbresult->num_rows == 0)
{
echo "<h1 style='text-align: center;'>No Data Found</h1>
}
else
{
echo "
<br><br>
<h1 style='text-align: center; color: blue;'>$Hotel Name</h1>
<img src='$Image'><br>
$HotelDetail<br>
$Review
";
}
?>
I have no problem to display the content on the page, what I want is, show the content on the new generated pages for each database row instead of using a unique URL parameter.
Change
https://domainname.com/hotel-details/?hotelcode=First-Hotel
to
https://domainname.com/hotel-details/First-Hotel

Related

Display images from different folders

using external web pages customers can create a ticket with different values and upload images. All these values are passed to an internal system that allows people to manage the tickets but are shown only the database values and not the images on a simple php page. When a ticket is created the ticket and the images folder (that is automatically created) share a common and unique ID. So the ticket is the same as the folder name.Searching for the ID the pages with all the data is shown using this:
<?php
$link = mysqli_connect("xxx", "xxx", "xxx", "xxx");
if($link === false){
die("ERRORE: DB error. " . mysqli_connect_error());
}
$num = $_GET['ticket_id'];
$query = "SELECT * FROM tickets WHERE ticket_id = '$num'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
?>
<form action="edit.php" method="post">
<table id="myTable">
etc
I tried using something like glob function but I always get "no images to display"
<?php $thumbs = glob("2021/ticket_att/$num/*.{jpg,jpeg,png,gif}", GLOB_BRACE)?>
<?php
if(count($thumbs)) {
natcasesort($thumbs);
foreach($thumbs as $thumb) {
?>
<li>
<img src="<?php echo $thumb ?>" width="50%" alt="ticket image" />
</li>
<?php
}} else {
echo "No images to display!";
}
?>
Where am I getting wrong?
Thank you!
--> UPDATE <--
The glob function works if I change the value of $num into a fixed value (for example
<?php $thumbs = glob("2021/ticket_att/123456/*.{jpg,jpeg,png,gif}", GLOB_BRACE)?>
but if I check the value of $num is correct. Maybe the functions doesnt' read a variable value?
Thanks!

Create dynamic category menu in PHP

I'm new to coding and PHP and I want to create an online shop for a school project. I want simple code that selects categories in my DB shows them on a home page and when click on it select all things in that category and shows them. I wrote code that can create buttons for each category that are in my database but I have no idea how write code that when the user clicks on a button selects that category.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "123456789";
$dbname = "shopdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT category FROM good ";
$result = $conn->query($sql);
echo "category: ";
while($row = $result->fetch_assoc()) {
echo "<button>$row[category]</button>" ;
}
$conn->close();
?>
If you want to use only php you can redirect the use after he clicks the category.
while($row = $result->fetch_assoc()) {
$category = $row["category"];
echo "<a href=’?category=$category’>$category</a>" ;
}
Make the link look like a button with css.
So when the user clicks on the link it redirects him to the same page he is currently but it adds the
?category in the end of it. home.php?category=clothes.
In the same page use $_GET to get the ?category value from the url.
And make a query to get your items for the category.
if(isset($_GET[’category’])){
$category = $_GET[’category’];
$sql = mysqli_prepare(”SELECT * FROM items WHERE category = ?”);
$sql->bind_param(”ss”, $category);
$sql->execute();
while($row = $sql->fetch_assoc()) {
echo $row[”name”];
}
}
And you should do this before you close your mysqli connection.
You may need to change the query because i don’t know your tables and you could maby wrap the while loop inside a div or something. But i hope you get the basic idea.
If you want it to look more fancy you could do the same with jQuery and Ajax since you have the jQuery tag.
Make a click function for your category buttons. You should add classes on them. <button class=’category’>$row[category]</button>.
Make another file for your ajax requests to get your items for the category.
$(”.category”).click(function() {
var category = $(this).text();
$.ajax({
url: ”items.php?category=” + category,
type: ”GET”,
success: function(items) {
console.log(items);
}
});
});
In your items.php or whatever you named it you can basically do the same php code that i wrote earlier.
Get the category name from the url with $_GET[’category’] and use it to search the items from your database.
The items variable that we have as parameter in the ajax success function, now contains everything that items.php echo out.
Now continue to handle the data in the items variable and display it.
You must pass your php variable in your html code. After in your html code try this.
<?php while( $row = $result->fetch_assoc() ) { ?>
<button><?php echo $row[category] ?></button>
<?php } ?>

How to use names instead of id's in dynamic webpages

I just started learning php and mysql and i might already be way ahead of myself. The thing i would like to create is a webpage where ppl can sign up for an event, so far so good, the form to submit their first name, last name, age and email adress is working and its actually sending te information to the database.
Next thing i want to create is a page where i can display all the database records submitted (except for the email adress). This is also working, but I wanted to play around with dynamic urls.
When i visit my page http://www.example.com/ppl.php?id=1 i get the information of the first database record displayed but i also wanted to see if i could get this to work with names instead of ids so i tried to edit my code and use http://www.example.com/ppl.php?name=john this does only return an error and however there are a few people called john in the database no records are displayed.
So i would like to know if what i want is actually possible and how do i get this to work with my current code.
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "event";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$firstname = 'firstname';
$lastname = 'lastname';
$age = 'age';
$sql = "SELECT * FROM people WHERE id = $id";
$result = $conn->query($sql);
echo "<table id='display' width='600' align='center'>";
echo"<tr><td> Firstname</td> <td> Lastname</td> <td> Age</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr><td width='33%'> $row[$firstname]</td> <td width='33%'> $row[$lastname]</td> <td width='33%'> $row[$age] cm</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Try to change the query:
$sql = "SELECT * FROM people WHERE id = $id";
To:
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name LIKE '%$name%'";
Then echo for each one John you find.
Also consider using CSS like this.
<style>
#display {
width: 600px;
}
#display td {
width: 33%;
}
</style>
You should be looking for two separate $_GET keys: id OR name.
<?php
if (isset($_GET['id'])) {
// logic to get row by ID
} elseif (isset($_GET['name'])) {
// logic to get row by Name
} else {
// logic if no $_GET keys are set
}
I would recommend not using the name field for a find because it's not a primary key in your database - it may not be unique. Your query may return multiple results depending on what data is being stored.
Edit: To answer the question of where to place this in the code sample above, consider placing it where the query string is declared.
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM people WHERE id = $id";
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name = '$name'";
}
From there you can keep the same query execution logic. But as I stated, I'd advise against using the name field as a key because it may not be unique.

PHP mysql not showing up admin panel feature

so i've been up for a long time working on this. So basically want I need to do is make an add, update, delete user table. Right now i'm currently just working on a table that shows what I have in my database and options to edite, delete, or add.
I have 2 tables in my database.
Links Table with the fields of : PID, LinkName, AnchorText, CategoryID, CategoryName
linkCategory table with the fields of : CategoryID, CategoryName
here's what I have so far.... and it's not showing up at all. No errors or anything.
<?php
// acquire shared info from other files
include("dbconn.inc.php"); // database connection
include("shared.php"); // stored shared contents
// make database connection
$conn = dbConnect();
print $HTMLHeader;
print $PageTitle;
?>
<script>
function confirmDel(title, pid) {
// javascript function to ask for deletion confirmation
url = "admin_delete.php?pid="+pid;
var agree = confirm("Delete this item: <" + title + "> ? ");
if (agree) {
// redirect to the deletion script
location.href = url;
}
else {
// do nothing
return;
}
}
</script>
<?php
// Retrieve the product & category info
$sql = "SELECT Links.PID, Links.AnchorText, linkCategory.CategoryName FROM Links, linkCategory where Links.CategoryID = linkCategory.CategoryID order by linkCategory.CategoryName";
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)){
$stmt->execute();
$stmt->bind_result($PID, $Title, $CategoryName);
$tblRows = "";
while($stmt->fetch()){
$Title_js = htmlspecialchars($Title, ENT_QUOTES); // convert quotation marks in the product title to html entity code. This way, the quotation marks won't cause trouble in the javascript function call ( href='javascript:confirmDel ...' ) below.
$tblRows = $tblRows."<tr><td>$Title</td>
<td>$CategoryName</td>
<td><a href='admin_form.php?pid=$PID'>Edit</a> | <a href='javascript:confirmDel(\"$Title_js\",$PID)'>Delete</a> </td></tr>";
}
$output = "<table border=1 cellpadding=4>\n
<tr><th>Title</th><th>Category</th><th>Options</th></tr>\n".$tblRows.
"</table>";
$stmt->close();
} else {
$output = "Query to retrieve product information failed.";
}
$conn->close();
?>
<?= $SubTitle_Admin ?>
<br>
| Add a new item |<br>
<?php echo $output ?>
<?php print $PageFooter; ?>
</body>
</html>
This is my first page, I still have to put in the PHP for edit, update, and delete... but can't even get my main page to show up. A bit lengthy, but I need to get this done. If anyone could help me out, or point me the right direction... I would be grateful. Here is a link to what it should look like http://omega.uta.edu/~cyjang/ctec4321/lab/productList2/admin_productList.php. When I try to pull my own up it's a blank page... like this: http://omega.uta.edu/~dxh6110/4321/in%20class/linksadmin/admin_productList.php

HTML link with a php action

I am creating a website that stores information of homes like address, city etc. I got the upload to database part done and I got the search the database and display the information done.
But now my plan with that is you get the search results and from there your suppose to get the option to view the full profile of that home via link. Displaying the full profile with the information gathered from the database is already done through a separate php file. Now when I link the php file it will only display the last column in the database. How can I link it so when I click on "view full profile" it will connect to the correct data/profile that corresponds to the different address or price. Or if i cant use an html link what can I use? Is that impossible?
here is the code that displays the search results I have successfully been able to search the database and display it
<?php
if($sql->num_rows){
while ($row = $sql->fetch_array(MYSQLI_ASSOC)){
echo '<div id="listing">
<div id="propertyImage">
<img src="images/'.$row['imageName1'].'" width="200" height="150" alt=""/>
</div>
<div id="basicInfo">
<h2>$'.$row['Price'].'</h2>
<p style="font-size: 18px;"># '.$row['StreetAddress'].', '.$row['City'].', BC</p>
<p>'.$row['NumBed'].' Bedrooms | '.$row['NumBath'].' Bathrooms | '.$row['Property'].'</p>
<br>
<p>View Full Details | Get Directions
</div>
</div>';
height="150" alt=""/>';
}
}
else
{
echo '<h2>0 Search Results</h2>';
}
?>
Here is the php to display the information outputtest.php
<?php
mysql_connect("localhost","root","31588patrick");
#mysql_select_db("test") or die( "Unable to select database");
$query="SELECT * FROM propertyinfo";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$varStreetAddress=mysql_result($result,$i,"StreetAddress");
$varCity=mysql_result($result,$i,"City");
$varProperty=mysql_result($result,$i,"Property");
$varNumBed=mysql_result($result,$i,"NumBed");
$varNumBath=mysql_result($result,$i,"NumBath");
$varPrice=mysql_result($result,$i,"Price");
$varEmail=mysql_result($result,$i,"Email");
$varPhone=mysql_result($result,$i,"Phone");
$varUtilities=mysql_result($result,$i,"utilities");
$varTermLease=mysql_result($result,$i,"TermLease");
$varNotes=mysql_result($result,$i,"Notes");
$image1=mysql_result($result,$i,"imageName1");
$image2=mysql_result($result,$i,"imageName2");
$image3=mysql_result($result,$i,"imageName3");
$image4=mysql_result($result,$i,"imageName4");
$i++;
}
?> html code will go after this
Thanks
edit its working
<?php
////////////using mysqli to connect with database
$mysqli = new mysqli("localhost","root","31588patrick", "test");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
///////////set variables
$record_id = $_GET['record_id'];
$sql = $mysqli->query("select * from propertyinfo where StreetAddress like '%$record_id%'");
if($sql === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if($sql->num_rows){
while ($row = $sql->fetch_array(MYSQLI_ASSOC)){
$varStreetAddress=$row['StreetAddress'];
$varCity=$row['City'];
$varProperty=$row['Property'];
$varNumBed=$row['NumBed'];
$varNumBath=$row['NumBath'];
$varPrice=$row['Price'];
$varEmail=$row['Email'];
$varPhone=$row['Phone'];
$varUtilities=$row['utilities'];
$varTermLease=$row['TermLease'];
$varNotes=$row['Notes'];
$image1=$row['imageName1'];
$image2=$row['imageName2'];
$image3=$row['imageName3'];
$image4=$row['imageName4'];
}
}
If the link you are using is only fetching the last record in the database table, then the underlying query that is used must be fetching the last record instead of the intended record. Am I correct in understanding the problem you are having? That any link you use is just returning the last record in the database?
Posting a code snippet will help the community take a closer look.
in your php file, you run a query for all records, but ...
$record_id = mysql_real_escape_string($_GET["record_id"]);
$query="SELECT * FROM propertyinfo WHERE id=$record_id";
your link needs to attach a parameter that will allow you to query for a specific record.
a href="outputtest.php&record_id=8"
AND you would also want to check what is in the GET parameter before sticking it into the query! I know mysql_real_escape_string is outdated.

Categories