I have created my own table on my wordpress database and created the filter search form. Now, my problem is that, I dont know how to connect my database to my search filter form in wordpress.
Here is the process, I send the keyword from index.php to result.php, and it shows nothing, just a blank page.
Here's my code:
<?php
define('WP_USE_THEMES', false);
global $wpdb;
$destination = $_POST["destination"];
echo "Welcome test" . $destination;
$sql = "SELECT * FROM rates WHERE location = '" . $destination ."';";
echo $sql;
echo "search this";
foreach ( $wpdb->get_results($sql) as $result ) {
echo "search for". $result->location;
}
?>
wp-content/themes/Your-Theme-Name/result.php
<?php
/*
* Template Name: MyResultPage
*/
/* You can also use require_once('wp-load.php'); */
get_header();
global $wpdb;
$destination = $_POST["destination"];
$table = $wpdb->prefix . "rates";
$sql = "SELECT * FROM `". $table . "` WHERE location = '". $destination. "'" ;
$result = $wpdb->get_results($sql);
foreach($result as $res) {
echo "search for". $res->location;
}
?>
Then, you create a new page in your wordpress admin and set the template to result.php template name: MyResultPage (for example).
you should either include wp-config.php file in the header of the file which will include all the relevant files in your page.
Can you plz check below code and it output.
i added one page in root directory of WordPress and make one page and add this code.
test.php
<?php
define('WP_USE_THEMES', false);
require_once('wp-load.php');
global $wpdb;
$result = $wpdb->get_results(("SELECT * FROM {$wpdb->prefix}posts WHERE post_type = 'page'"), ARRAY_A);
foreach( $result as $key => $val )
{
echo '<p>Title - '.$val['post_name'].'</p>';
echo '<p>ID - '.$val['ID'].'</p>';
}
?>
Now here is out put of this page it shows all page title and id.
Output:
<p>Title - sample-page</p>
<p>ID - 2</p>
<p>Title - sample-page1</p>
<p>ID - 3</p>
Related
So I've been working on this website a long time but the problem is most of it is MYSQL, which of course isnt very secure, so now I'm trying to update all the PHP to PDO, so far I've only managed to get the connect.php working (in the first code below). My main issue is wthin the 2nd code below, on my reviews page I'm having a hard time fetching ALL the reviews from database including (cid,uid,username,date,message & rating) and then ORDER BY DESC, I have used multiple guides but they all seem to show a different way of doing it...
<?php
$host = 'localhost';
$dbuser = 'B99';
$dbpwd = 'testpass';
$dbname = 'admin';
//set DSN//
$dsn = 'mysql:host=' . $host .';dbname=' . $dbname;
//Create PDO instance//
//Attempt MySQL server connection.//
$pdo = new PDO($dsn, $dbuser, $dbpwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and the FetchAll code here:
<?php
include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");
$sql = $pdo->query("SELECT * FROM `reviews` ORDER BY `cid` DESC");
$stmt = $pdo->prepare($sql);
$stmt->execute(['cid']);
$reviews = $stmt->fetchAll();
foreach ($reviews as $fetch) {
?>
<div class="eachreview" style="background-color:royalblue;">
<?php echo $fetch['rating']; ?>
<?php echo $fetch['uid']; ?>
<?php echo $fetch['message']; ?>
<?php echo date("d/m/Y" ,strtotime($fetch['date'])); ?>
</div>
<?php
}
?>
UPDATED CODE Kinda working but displaying 1/1/1970 and no other data
<?php
include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");
$stmt = $dbh->prepare("SELECT * FROM `reviews` WHERE cid = :cid");
$stmt->execute(array(':cid' => "cid"));
$fetch = $stmt->fetchAll();
{
?>
THIS CODE BELOW WORKS! :)
<?php
include("/var/www/vhosts/my-web.co.uk/httpdocs/PHP/connect.php");
$stmt = "SELECT * FROM `reviews`";
$result = $dbh->query($stmt);
foreach ($result as $fetch) {
?>
<?php echo $fetch['message']; ?>
I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>
I need to create a div that only shows the information of the database, how should i connect the div to mysql so it only shows my database information?
I'm not sure I'm understanding your question... but I'll give it a try. The code below this will select whatever you tell it to from the database and echo it into a table.
<?php
$db = mysqli_connect('host', 'username', 'password', 'database');
$sql = "SELECT * FROM database"
mysqli_stmt_bind_param($db, "params here", your info here);
$res = mysqli_stmt_execute($sql);
mysqli_stmt_close($sql);
mysqli_close($db);
echo "<table>";
while($row = mysqli_fetch_array($res)){ //Creates a loop to loop through results
echo "<tr><td>" . $row[''] . "</td><td>" . $row[''] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
?>
please find below a script in php that that fetch data from my database company, the database is in phpMyadmin
I understand that there are secure ways to fetch data. My question is
Can I improve the code below using mysqli to fetch instead of mysql_query.
<?php
get results from database. Can I improve the code below using mysqli to fetch instead of mysql_query in the following line?.
$result = mysql_query("SELECT * FROM customer")
or die(mysql_error());
tables begins here with the customer id and customer name
echo "<table >";
echo "<tr>
<th>ID</th> the customer id
<th>Name</th> the customer name
</tr>";
// loop through results of database query, displaying them in the table
the table below display the columns in html using mysql fetch array. all data is displayed.
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
my purpose is embed the php in html in another way using msqli
echo "<tr>";
echo '<td>' . $row['CustomerID'].'</td>';
echo '<td>' . $row['Name']. '</td>';
echo "</tr>";
}
echo "</table>";
?>
my purpose is embed the php in html in another way using msqli
Just replace all the mysql with mysqli
$result = mysqli_query("SELECT * FROM customer");
while($row = mysqli_fetch_array( $result )) {
If you wanna keep it simple
Or do it like this...
/*Your connection info goes here...*/
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM customer";
if ($result = $mysqli->query($query)) {
echo "<table ><tr><th>ID</th><th>Name</th></tr>";
/* fetch results by row */
while ($row = $result->fetch_row()) {
echo "<tr><td>' . $row['CustomerID'].'</td><td>' . $row['Name']. '</td></tr>';
}
/* free the result set */
$result->close();
}
/* close the connection */
$mysqli->close();
I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX";
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.