Wordpress Ninja Forms view submitted data - php

I'm using the NinjaForm plugin on my Wordpress site, which is working well but we're looking to create a custom .php page to output some of the submitted data.
Our current file is
<?php
$username = "SQLuser";
$password = "SQLpass";
$host = "localhost";
$connector = mysql_connect($host, $username, $password)
or die("Unable to connect");
$selected = mysql_select_db("wordpress", $connector)
or die("Unable to connect");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Report</title>
</head>
<body>
<!--right-->
<?php
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM wp_postmeta WHERE Meta_Key LIKE '%field%'");
?>
<table>
<thead>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo
"<tr>
<td>{$row['post_id']}</td>
<td>{$row['meta_key']}</td>
<td>{$row['meta_value']}</td>
</tr>";
}
?>
</tbody>
</table>
</body>
</html>
<?php mysql_close($connector); ?>
Mostly butchered from Display data from mysql/phpmyadmin on html page but this is displaying data in one long list like this screenshot
Our aim is to get this data in a table with the headers for for each field
e.g.   
_field_5 = Name,  
_field_8 = Food,  
_field_6 = Can attend
      
  
   
 
The DB format is like this image, so the data isn't kept in separate columns in the first place, so hopefully we're able to rearrange this using php.
Any advice?

So, first a couple of things to note relating to best / safest practice in WP.
Don't create 'custom' pages. Create a custom template then add your php to that. Now create a page in WP, and assign it the relevant page template. This way you can make use of WordPress properly.
Use the WP functions for querying the database rather than querying the db directly via PHP
<?php
$querystr = "SELECT * FROM wp_postmeta WHERE Meta_Key LIKE '%field%";
$output = $wpdb->get_results($querystr, OBJECT);
?>
Now, with that in mind you need to construct the page accordingly. Without full access to your current results page I can only vaguely guess at how to format your markup. But, something like this should get you most of the way:
<table>
<thead>
</thead>
<tbody>
<?php
if($output){
foreach ($output as $row){
echo
"<tr>
<td>{$row['post_id']}</td>
<td>{$row['meta_key']}</td>
<td>{$row['meta_value']}</td>
</tr>";
}
}
?>
</tbody>
</table>

Related

Empty Select HTML (Dropdown Box) using PHP to fill from a MySQL Database

I am apologizing ahead, this is my first question here and I am still a student.
No time to waste.
I am making a website where you are given drop down boxes to choose CPU, Motherboard, Memory and the rest of your computer parts and sent via email or printed out or generate a code unique to you and your build, so the build is stored in the code. That all comes later.
My problem is that the computer parts listed in tables in database wont load in the box (or dropdown box) as using PHP to generate it from the DB. I've already searched many questions and answers on Stackoverflow but to no avail and I want to kill myself (not really, I am not suicidal at all, it's a figure of speech)
Here is what I got. Then I will explain all the problems that have been popping up.
index.php
<?php
include_once 'func.inc.php';
connectDB();
testDB();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PC Builder</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body background="background.jpg">
<header>
<h1>PC Builder</h1>
</header>
<section>
<table>
<tr>
<td class="titlecolomn">CPU</td>
<td><?php queryCPU(); ?></td>
</tr>
</table>
</section>
</body>
</html>
<?php closeDB(); ?>
func.inc.php
<?php
include_once 'db.inc.php';
function connectDB(){
$conn = new mysqli($servername, $username, $password, $dbname);
}
function testDB(){
if ($conn->connect_error) {
die("Debug: Connection Failed: " . $conn->connect_error);
}
echo "Debug: Connection Successful.";
}
function closeDB(){
mysqli_close();
}
function queryCPU(){
$queryCPU = "SELECT * FROM CPU";
$db = mysqli_query($db, $queryCPU);
echo '<select name="selectCPU">';
echo '<option value = "SelectCPU"> Select CPU </option>';
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
echo '</select>';
}
db.inc.php
<?php
$servername = "localhost";
$username = "theUsername";
$password = "thePassword";
$dbname = "tableName";
?>
MySQL DB structure.
WebsiteName_PCBuilder
CPU (Table)
ID (Int, AUTO_INC)
Name (Varchar, 30)
ClockSpeed (Decimal 10,2)
Cores (Int)
Price (Decimal 10,2)
Here are the problems.
Whatever kind of password or username or database name or localhost name I put ConnectDB(); always returns
Debug: Connection Successful.
As such the <Select> </Select> is loaded with nothing in it but
'<option value = "SelectCPU"> Select CPU </option>'.
Also, if you know a better or alternative way of doing this, please do recommend it. I am quite flexible changing the entire thing if it it can work.
Here is the website. http://pcbuilder.tariqsendi.ml/
In above provided code, I snipped out the unimportant parts.
Ignore the Main Domain.
Thank you so much, in advance.
That's because you overwriting the same var.
Change
while ( $db=mysqli_fetch_assoc($db)) {
echo '<option value="{'.$db[ID].'}">'.$db[Name].'</option>';
}
With
while ($row = mysqli_fetch_assoc($db)) {
echo '<option value="{'.$row['ID'].'}">'.$row['Name'].'</option>';
}
while ( $row=mysqli_fetch_assoc($db)) {
echo '<option value="'.$row['ID'].'>'.$row['Name'].'</option>';
}

How to get data from a MySQL database and insert it into text

I've been working on a website of mine- it's a shop for different items (it's also my first website). I just got done with the HTML/CSS part of the website but I want to make it more dynamic and easier to edit without having to change multiple pages at once. One way I figured I could do this and also make it easier to implement a website search is by having the names and prices of the items in a database and having PHP code retrieve the name and price and insert it underneath the image of the item. Unfortunately, I have absolutely no idea how to go about this. I've tried looking for other people with similar questions but none of them seem to be specifically what I'm looking for. I'll put my PHP code below and then I'll put some html code that shows where I want to put the information.
<?php
$servername = "localhost";
$username = "root";
$password = "testpw";
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
}
$sql = "SELECT id, name, price FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " .$row["id"]. " " .$row["name"]. " " .$row["price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So that's the PHP code that I use to get the information for each item. The problem though is that it gets the information for every item and displays it at once. I want the code to check for the ID of the item and then retrieve the stats about it and display them. This means if I want to rearrange items in the shop I only have to change the ID- which makes it much much easier for me to manipulate the shop and the items in it. Below is the HTML code for the items.
<div id="images">
<figure>
<img class="gunimage" id="(THIS IS THE ID USED TO GET THE INFO)" src="idk.png" width="225" height="190" alt="">
<figcaption><h3>Name: (INSERT NAME HERE USING PHP) </h3></figcaption>
<figcaption><h5>Price: (INSERT OTHER PRICE HERE)/month</h5></figcaption>
<figcaption><div id="tfbutton5"><form action="buy.html"><input type="submit" value="Rent" class="tfbutton5"></form></figcaption>
</div>
</figure>
</div>
I labeled where I want the info to go, and I want to have the ID thing so the PHP code knows what item it is. I know both codes work separately, as I've tested both of them many times. Sorry if my question is really long, I wanted to make it as specific as possible so it's clear what my problem is. Please excuse if my code requires a lot of changes to make applicable in the situation I'm describing, as I only could figure out how to make something that lists out the info for every item. Any help would be appreciated. Thank you.
If you wanted to do something more you could put in a file called
'connection.php' or something more descriptive
try {
$servername = 'localhost';
$username = 'root';
$password = 'testpw';
$dbname = 'testdb';
$db = new mysqli($servername, $username, $password, $dbname);
} catch(Exception $e) {
echo $e->error_list;
exit;
}
function execute_query($con, $query, $variables) {
$stmt = $con->prepare($query);
$stmt->execute($variables);
return $stmt;
}
you could split these the top part in a connection.php while the function in a function.php file if you have more than one function.
include ('connection.php');
$id_number = $_GET['id'];
# !! NOTICE if grabbing | my understanding another page |
// filter if grabbing from GLOBAL Variable $_GET
$id = filter_var($id_number, FILTER_SANITIZE_NUMBER_INT); //take out
if not grabbing from outside source.
$con = $db;
try {
$query = 'SELECT t.id as id , t.name as name, t.price as price
FROM items as t
WHERE t.id = :id';
$variables[':id'] = $id;
$items = execute_query($con, $query, $variables);
}catch(mysqli_error_list $e) {
echo $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="images"><!-- i am guessing you want it within this div-->
<?php if(isset($item)) { ?>
<?php foreach ( $items as $item) { ?>
<figure>
<img class="gunimage" id="<?php echo $item['id']; ?>"
src="idk.png" width="225" height="190" alt="<?php echo $item['name'];
?>">
<figcaption><h3>Name: <?php echo $item['name']; ?> </h3>
</figcaption>
<figcaption><h5>Price: <?php echo $item['price']; ?> </h5>
</figcaption>
<figcaption>
<!-- instead of a id tfbutton5 needs to be a class otherwise your
going to have an issue here when it loops, you will have an error-->
<div class="tfbutton5"><form action="buy.html"><input
type="submit" value="Rent" class="tfbutton5"></form>
<!--also, not sure why you have an Id and a class named exactly
identical but it is bad practice. sorry do not do it. -->
</figcaption>
</div>
</figure>
<?php } ?>
<?php } ?>
</div>
</body>
</html>
if you wanted an image source, you would need to enter that into a database and connect your Items table to an Image table with that table having say..rows id, image, and item-id. then use the item-id as a point between the item and the image

Open new page with table Data from previous page

I'm building a website for the company I work for that is going to eventually replace the CRM we are using. Right now I have created a simple php file that creates a table of simple/basic values (I'm trying to test the concept before I scale it up to the read deal). I am using a WHILE loop to generate the table by pulling data from the server. I was able to make the first column in each row into a clickable link that will open to a new page. On this page, I want to post more detailed data that can be edited. For example, in the display.php file that shows the table created with the while loop I will have a property address, a city name and a person who is working to either buy or sell that property. When the user clicks on the first address, I want it to open into a page that will display information like bedrooms, bathrooms, square footage, subdivision, asking price, etc. It would be nice to have each of those fields editable too, but that's a different thing to tackle. Right now, I'm concerned with being able to click on one property and have it open up with the correct data in the next page. Right now, it successfully opens the page but it only shows the data from the first row no matter which row I click on in the table.
Here is the code that I have for the page that displays the table:
<?php
session_start();
if(isset($_SESSION['id'])) {
$username = $_SESSION['username'];
$userId = $_SESSION['id'];
} else {
header('Location: index.php');
die();
}
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
?>
<html>
<head>
<title>Display Data</title>
<body>
<table action="" method="post" class="table" id="example">
<tr>
<th>Address</th>
<th>City</th>
<tr>
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
//I'm trying to figure out how to pass the record's ID as a way of keeping track of which record I want to look at when I open it in the next page. I don't know how to put the id in the link so that it carries through to the next page.
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
</tr>
</table>
</body>
</head>
</html>
Here is my code for the page that should open up with a more detailed "profile view" of the data:
<?php
//connect to db
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
//I tried to incorperate "WHERE leadid = '$_GET['leadid']'" in line 10 to define the lead id that is associated with the record that was selected in display.php and shoould be opened/shared to this page
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
//I tried to create a $_GET variable that calls on the record id that I am trying to pass from the display.php file to this page
$leadid=$_GET['leadid'];
?>
<html>
<head>
<title>Show Stuff</title>
<body>
<h1>Show Stuff Here</h1><br>
<?php
echo "<p>Test</p><br>";
//I only have one piece of information here to test if it works in the first place. Once it does, I'll add the rest of the fields to display
echo "Is ".$leadid=$leads['leadid']." your ID number?";
?>
</body>
</head>
</html>
Lastly, I am using sessions on here since eventually there will be various users with different levels of access to view and edit things. For now, it's really not too functional other than to log in and log out. It's also not very secure. But I'm more focused on figuring out the mechanics of one thing at a time as I build. It's no where near ready to be used. But I'm hopeful that I'll get there soon. You'll have to excuse my simple code, I'm just learning and teaching myself on my spare time since our company refuses to hire someone to actually do this...
You're putting $leadid in the URL parameters in the table, but you never set this variable.
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
$leadid = $leads['leadid'];
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
Then you should be able to use $_GET['leadid'] in showstuff.php to show the information for the lead that they clicked on.
$leadid = intval($_GET['leadid']);
$sql="SELECT * FROM leads WHERE leadid = $leadid";
First, in your table, you have to put like this:
while($leads=mysqli_fetch_assoc($records)){
echo '<tr>';
echo '<td><a href="showstuff.php?leadid='.$leads['id'].'" >'.$leads['address'].'</a></td>';
echo '<td>'.$leads['city'].'</td>';
echo '</tr>';
}
Like this your link leadid will have a value.
Use simple quote ' ' for html value, it's faster and better for PHP. ;)
In your second file, make like this:
$leadid=$_GET['leadid'];
$sql="SELECT * FROM `leads` WHERE `id`='$leadid' ";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
It's better to put for the table and columns names and ' ' for values.
In $leads array, you 'll have all data.
You can "print" it like this:
echo 'The ID is '.$leads['id'].' and the name is '$leads['name'];
I hope it's useful!

Mysql invalid argument

For some reason the code below provides me with the following error:
Warning: Invalid argument supplied for foreach(). I tested the query in PHPmyadmin and the query works on its own. For some reason it doesn't work in the context if this php document. Are there any specific mistakes that are leading to this?
Thanks
<!Doctype <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th> Course </th>
<th> Instructor </th>
<?php
$db = new PDO("mysql:dbname = 282exam; host = localhost", "root", "root");
$rows = $db->query("SELECT c.Name, i.Name
FROM course c
JOIN instructor i ON i.CId = c.Code");
foreach ($rows as $row){
?>
<tr>
<td> <?php print $row["c.Name"] ?></td>
<td> <?php print $row["i.Name"] ?></td>
</tr>
<?php
}
?>
</body>
</html>
instead of
foreach ($rows as $row){
do
while($row = $rows->fetch()){
(I just found out that change is optional, your way should work fine but this is how I've always done it)
And you don't need to specify the table alias in the result array
$row["Name"]
But you should specify an alias for each column if they're both the same...
SELECT c.Name as cname, i.Name as iname
$row["cname"] , $row["iname"]
Also, what Fred said:
then there should not contain any spaces in new PDO("mysql:dbname =
282exam; host = localhost" and
php.net/manual/en/pdo.error-handling.php would have thrown you an
error about it. see the manual php.net/manual/en/pdo.connections.php –
Fred -ii-
In other words: Change this to..
$db = new PDO("mysql:dbname=282exam;host=localhost", "root", "root");
AND
Missing <doctype> at the top that may cause errors
Missing </table>
Also, you're using <th> tags but no table header tags. Check out one of these links to figure out the correct table syntax.

a redirection to the profile

Ive got a code running smoothly which shows the list of people who are level 8 as shown below
I want when a person click on the username of the people it redirects them to their profile, actually i've got no clue or ideas of how could that be done. So i need a little bit of help to get some points on this.
Here is the code to show the above output
<?php
$lvl8 = 0;
$content = "";
$query = $koneksi->prepare("SELECT `user`, `level`, `LastOnlineDate` FROM `playerdata` WHERE `banned`=0 AND `level`=8");
$query->execute();
while($data = $query->fetch())
{
$lvl8++;
$content .= "<tr><td>".$lvl8."</td>";
$content .= "<td>".$data['user']."</td>";
$content .= "<td>".$data['LastOnlineDate']."</td></tr>";
}
?>
<table class="table table-bordered">
<thead>
<tr>
<td colspan='6'><h4><small>Level 8 - Trusted Admin (Total <?php echo $lvl8 ?>)</small></h4></td>
</tr>
<td><h5>Number</h5></td>
<td><h5>Username</h5></td>
<td><h5>Last Login</h5></td>
</thead>
<?php
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>No rows found</small></td></tr>";
}
echo $content;
?>
</table>
first thing you should do is, have an a tag for name, like this
$content .= "<td><a href='link to a new file?id=userid from database'>".$data['user']."</a></td>";
In the new page, you can capture the id of the user, run a query to fetch the details of obtained id and then show the details obtained from database.
Create a http query or post form for your action.
like this in your foreach loop.
GET
<?php echo $username ?>
in your ending script for example a controller in an mvc architecture:
$id = $_GET['user_id'];
// do database stuff and view
Do your query using $id and fetch the result then display your view.
Basically you iterate over user id's to create links that carry the id of the clicked user in order to fetch the selected id.

Categories