I am making posts of computer builds. I have a completely separate MYSQL database that I track computer components, assigned to each build. For instance, BuildID = 4 will have "Asus Rampage VI Extreme Motherboard x299", Core i9 7980xe Extreme LGA 2066" as values that come from the following query:
"SELECT BCats.Cat, BParts.ItemName, BParts.ItemSKU, BParts.ItemURL, BParts.ItemPrice, BParts.Qty, BParts.ItemPrice*BParts.Qty AS Price
FROM BParts
INNER JOIN BCats ON BCats.CatNo = BParts.ItemCat
WHERE BParts.BuildNo = 4 AND BParts.SystemNo = 1
ORDER BY BCats.CatNo ASC"
I need to take "BParts.BuildNo = 4" and turn it into a variable, such as "BParts.BuildNo = $buildNo". Then, for each customer that builds one of my desks, I can a photo gallery and just insert the shortcode [build] posts the table for all of the parts belonging to build number 4 (see it work at https://badvolf.com/en/declassified-systems-build/
Forgive me, but I am stumped at how to do it. I have searched everywhere, but nothing seems to fit what I am looking for, but I know that it can be done somehow. Here is what I have so far, and it generates the table that you see on the above link:
function wp_build_shortcode(){
$query = "SELECT BCats.Cat, BParts.ItemName, BParts.ItemSKU, BParts.ItemURL, BParts.ItemPrice, BParts.Qty, BParts.ItemPrice*BParts.Qty AS Price
FROM BParts
INNER JOIN BCats ON BCats.CatNo = BParts.ItemCat
WHERE BParts.BuildNo = 4 AND BParts.SystemNo = 1
ORDER BY BCats.CatNo ASC";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Build Name</title>
</style>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<col width="15%">
<col width="85%">
<col width="20%">
<thead>
<tr>
<th></th>
<th>Item</th>
<th>Qty</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<?php
if ($result = mysqli_query($GLOBALS['link'], $query)) {
while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row["Cat"]; ?></td>
<td><?php echo $row["ItemName"]; ?></td>
<td><?php echo $row["Qty"]; ?></td>
<td><?php echo $row["Price"]; ?></td>
</tr><?php }
} ?>
</tbody>
</table>
<?php
}
add_shortcode('build', 'wp_build_shortcode');
?>
So, how can I do something like [build="4"] and pass that value on to the query? Thank you in advance!
You need to give your function at least one parameter. For Example wp_build_shortcode($attributes). $attributes will be an array with the parsed shortcode parameters. In your case ['build' => '4']. Then you can assign it to any local variable:$buildNo = issest($attributes['build']) ?
intval($attributes['build']) : 0;`. You can find more information here.
In WP shortcodes are accessible for very low privileged users (subscribers). Therefore you should treat the parameters as untrusted user input, and protect yourself from SQL injections and other exploits. In your case the intval in the above code should be enough, but prepared statements are a better practice.
Related
I setup a php file to pull data from a database, and list that on a table. I then made a simple search function to search that data, however I can't figure out how to implement a space when searching. For example, if I searched test 2 (test from one column, 2 from another) it won't display anything. However, if I were to search 'test2' or '2test' it displays all results. How would I implement that space into my code?
Here's my code:
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `master` WHERE CONCAT_WS(`id`, `office`, `firstName`, `lastName`, `type`, `status`, `deadline`, `contactPref`, `email`, `phoneNumber`, `taxPro`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `master`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "", "", "");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
echo "test";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="Untitled-1.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>ID</th>
<th>Office</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
<th>Status</th>
<th>Deadline</th>
<th>Contact Preference</th>
<th>Email</th>
<th>Phone Number</th>
<th>Tax Pro</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['office'];?></td>
<td><?php echo $row['firstName'];?></td>
<td><?php echo $row['lastName'];?></td>
<td><?php echo $row['type'];?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['deadline'];?></td>
<td><?php echo $row['contactPref'];?></td>
<td><?php echo $row['email'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
<td><?php echo $row['taxPro'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>```
A way to do this could be to have your string spillted up into words in php. You could use explode function for this (https://www.php.net/manual/en/function.explode.php)
And then write SQL where clause like this (im assuming you are using mysql):
WHERE col LIKE %word% OR col LIKE %word2%
This would be a bit inefficient, maybe the tool what you are looking for is elasticsearch? https://www.elastic.co/what-is/elasticsearch
Also, you should NEVER use . operator on an untrusted input. Because it creates MySQL Injection vulnerability. See this question for reference: How can I prevent SQL injection in PHP?
The simplest solution would be using FULLTEXT index in your mysql field. But I don't recommend using it on production. Instead, for actual projects external searching engine must be considered (e.g. Elasticsearch, etc.)
I'm currently working on a table that contains 'Name', 'Info', 'Price' and 'Duration'. However the PHP-Script is connected to a database.
I want to autofill the tablecells: 'Name', 'Price', 'Duration' via the Database by using PHP and SQL and that works perfectly fine for me. Though, I want to customize the content that's in the individual Info cells (e.g. Readmore jQuery and redirect to other pages).
I tried a little bit with using tags inside the Database and other weird stuff which, obviously, didn't work.
Is there a more elegant way of solving my problem than setting up a complete normal table without PHP/SQL, where I'd have to put in every bit of data about Name,Price and Duration manually?
<table class="table table-bordered table-hover tablesorter row sortable">
<thead>
<tr>
<th class="header">Name</th>
<th class="hidden-xs">Info</th>
<th>Price (in Euro)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<?php
//Connect to Database
$db=mysql_connect ("xxxx", "xxxx", "xxxx") or die ('Oops! Da hat wohl' . mysqli_error(). 'Mist gebaut');
//Choose Database
$mydb=mysql_select_db("massageke_de");
//Query Database
$sql="SELECT * FROM Angebote";
//-run the query against the mysql query function
$result=mysql_query($sql);
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$row['Info'];?<</td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Thanks in advance for helping.
Don't bother asking me additional questions.
P.S.: I hope you can help, without needing the CSS of Bootstrap, that I used.
P.P.S.:I know that my PHP-Script is not protected against PHP-Injection
(but I want to and will learn how to secure it)
Edit: As Jester asked for it. I made it quickly with photoshop because I think an image can express much better, what I want to achieve, than my poorly coding-skills.
Get to the image
Seems to me like the easiest way would be to just edit the info column in the database for each? If you want to do it in php i'd suggest making an array using the names (ids would be better but it seems you don't have access to those?) as keys:
$info['Aroma Teilkoerper'] = "Text about aroma teilkoerper";
$info['Aroma Ganzkoerper'] = "Text about aroma ganzkoerper";
and so on until you have all. Then in the loop:
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$info[$row['Name']];?></td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
Hoping that is a workable solution for you? (also you had a syntax error in your closing php tag.
echo $Name =$row['Info'];?< // <----- should be ?> of course
This is my first posting in SO, my apologize if I opened an existing question. As I couldn't find the result in Google. Sorry to said but I'm still fresh in PHP PDO and in learning stage.
Back to my question, currently I'm building a customer visit logs from my wife but I'm stuck with the result. I have two table which one stores the customer information and another table store the visit details. I uploaded the test table at here: SQL Fiddle
And below is my current coding and I'm using PHP PDO while
<?php
require_once 'dbconnect.php';
$p_id = $_GET['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT customer.fname, customer.lname, customer.gender, services.treatment, services.date
FROM customer LEFT JOIN services
ON customer.id = services.customer_id
WHERE customer.slug LIKE :id";
$q = $conn->prepare($sql);
$q->execute(array('id' => $p_id));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">
<h1>Customer Record</h1>
Name: <br />
Gender: <br />
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Gender</th>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname'])?></td>
<td><?php echo htmlspecialchars($r['gender']); ?></td>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
Seach Again
</body>
</div>
</html>
And I achieve as what SQL Fiddle result, but what I wanted is, the name and gender is not keep repeating.
I attached together with the screenshot:
Screenshot
What I want is as per the screenshot image, Name: John Doe and Gender: Male, should be on top and not keep on repeating while the table below show all the visit details. I tried to modified the code but it seems it don't really work out.
Please advise me as I'm really out of idea how to achieve what I want.
Thank you so much.
Since you do a LEFT JOIN in your SQL query, you know ahead of time that all of the fname, lname and gender values returned by $q->fetch() are going to be for the same customer.slug, right? So you can count on that.
My suggestion would be to instead use the fetchAll() function to get an array of all records for customer.slug, and then render that in your view. For example (haven't tested this) you could add the following after $q->setFetchMode(PDO::FETCH_ASSOC); ...
$cs = $q->fetchAll(); // customer services join
Then, in your <html> view, you could do something like the following:
<h1>Customer Record</h1>
Name: <?php echo htmlspecialchars($cs[0]['fname'].' '.$cs[0]['lname']); ?> <br />
Gender: <?php echo htmlspecialchars($cs[0]['gender']); ?> <br />
<table>
<thead>
<tr>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
Of course, it might also be a good idea to check to see that any records were returned by your query and display a "not found" message if not. After all, $cs[0] might be empty, giving you a PHP error.
Well i guess this must be a really dump question, but it's just that i 've been trying but with no results.
I have a webpage in which a display a list of books from my database, which works just fine. But now i'd like to add a dropdownlist so the customer will be able to filter books by category.
How can i acchieve this?.
I have this image so it may help you. Thanks in advance for your answwers!
<?php
require_once("../../seguridad/secure_user.php");
include("conexion.php");
$query = mysql_query("select * from libro order by id_libro desc");
?>
<div class="table-responsive">
<table class="table table-hover">
<thead bgcolor="3286CE">
<th><font color="#ffffff">Titulo
<th><font color="#ffffff">Categoria
<th><font color="#ffffff">Descripcion
<th>
</thead>
<?php
while ($datos = mysql_fetch_row($query)) {
?>
<tr>
<td><?php echo $datos[3]?>
<td><?php echo $datos[5]?>
<td><?php echo $datos[2]?>
<td><?php echo $datos[4]?>
<?php
}
?>
</table>
</div>
?>
1) upgrade your code mysql is depreciated and you should be using PDO or mysqli
2) Your query would need to be modified to allow the category to be changed in the WHERE clause.
$query = mysql_query("select * from libro order by id_libro desc WHERE category = $category");
You would restructure your code to allow these changes to take place, without knowing your table names we cannot restructure this for you.
A user chooses a value from a select box which is then passed via a form to another page which should show the mysql record of that selection. This is not showing any results, however the value is definitely being passed as it can be echoed out.
<?php
include("top.php");
$db = getConnection();
$eventID = $_POST['eventID'];
echo $eventID;
$queryEvent = $db->query("SELECT * FROM projectEvent WHERE eventID = '$eventID'");
$queryEvent->setFetchMode(PDO::FETCH_ASSOC);
$record = $queryEvent->fetchALL();
?>
<form name="form1" id="form1" method="post" action="deleteOpen.php">
<p> are you sure you want to delete the following Open Day? </p>
<table width="200" cellpadding="0" cellspacing="0">
<tr>
<th scope="row">eventID</th>
<td><?php echo $record -> eventID; ?></td>
</tr>
<tr>
<th scope="row">propertyID</th>
<td><?php echo $record -> propertyID; ?></td>
</tr>
<tr>
<th scope="row">eventDate</th>
<td><?php echo $record -> eventDate; ?></td>
</tr>
<tr>
<th scope="row">eventTime</th>
<td><?php echo $record -> eventTime; ?></td>
</tr>
<tr>
<th scope="row">eventDescription</th>
<td><?php echo $record -> eventDescription; ?></td>
</tr>
</table>
Can anyone suggest why the values are not shown in the table?
Thanks
to show data you shouldn't use POST method but GET instead.
either escape your values with PDO::quote or use prepared statements with prepare/execute instead of query()
if you are using ASSOC mode - why you are accessing them as a object properties?
Moreover, you actually have a nested array, but accessing it as a single object. if you don't need an array - don't use fetchAll() then
ALWAYS have error_reporting(E_ALL); in your scripts to see these silly mistakes.
You can concatenate the variable separately like this :
$queryEvent = $db->query("SELECT * FROM projectEvent WHERE eventID = ".$eventID.")";
Normally I do a little bit different of a method. It may not point out the problem but I think it will solve it. I usually dont use variables inside of quotes, but try below.
$sql = sprintf("SELECT * FROM projectEvent WHERE eventID = '%s'", $eventID);
$queryEvent = $db->query($sql);