I have a page that is querying a database quite a few times using php with that's being repeated; the query blocks are interspersed with html in between as well. An example is
<?php
--code here--
SELECT DISTINCT `Retailer`
FROM `product`
WHERE `Product` = 'iPad 2'
--continue code here--
?>
html content here
<?php
--code here--
SELECT DISTINCT `Brand`
FROM `product`
WHERE `Product` = 'iPad 2'
--continue code here--
?>
This is repeated a few times. This page that the queries sit on will need to duplicated for other pages but the "Product" line have to change (for example, Product = 'iPhone'). Currently, each of the queries is located within separate php code blocks so I have to go to each place where it is referenced to change it. Is it possible to have one location at the top of the document that I can change? If so, how do I do this?
I personally like using the $_GET variable for things like this, using mod_rewrite to generate necessary URLs that don't include the variables. I assume that some of your html changes along with the WHERE line of your query, too. You could try something like this:
Links to product pages
<ul>
<li>iPad 2</li>
<li>iPhone 4S</li>
</ul>
The products/index.php document
<?php
$product = $_GET['product'];
//various code
$retailer_result = mysql_query("SELECT DISTINCT Retailer FROM product WHERE Product = '$product'");
//more code
//define and require the html document
$product_page_dir = "products/pages/";
$product_page_path = $product_page_dir . $product;
require $product_page_path;
//more various code
$brand_result = mysql_query("SELECT DISTINCT Brand FROM product WHERE Product = '$product'");
//the rest of the code
This is the simplest way of doing it using this method. Don't forget to establish the connection MySQL and select the database before any queries. Also keep in mind that you should also probably include error handling. Note: the code above is untested.
You probably mean to write something like a function that you can reuse:
function get_product($column, $name) {
return db("SELECT DISTINCT `$column` FROM `product` WHERE `Product` = ?", $name);
}
Then just set a variable $product_name atop your page, and reuse that for issueing the queries. (If that's what you meant.)
$product_name = "iPad 2";
...
get_product("Retailer", $product_name);
...
get_product("Brand", $product_name);
...
get_product("Price", $product_name);
Related
I am trying to display field data in the WP front end using shortcodes from a new table.
See Table
After coming across many sources and research, I do not seem to find a simple way to display data in text (not table), contained within a specific field selected in the SQL query by means of SELECT FROM WHERE.
So far I called wpdb, selected the field, created a loop and echoed. But no results are displayed.
I also tried using print_r and implode but both failed too.
<?php
function Initial_Brief(){ global $wpdb;
$results = $wpdb->prepare( "SELECT 'Initial_Brief'* FROM `Portal_100` WHERE Project_Title = 'Project 1'");
foreach ($results as $result)
echo $result['results'];
}
add_shortcode('Initial_Brief','Initial_Brief')
?>
Many thanks in advance,
To share the logic of this, which I find quite powerful, is to use shortcodes for displaying all text on the website, enabling text edit from the front-end by creating an HTML form which updates the specific field. I will create an edit icon displayed on hover to an editor's role, clicked to trigger a popup with an html form which calls a function to update the specific field in the database.
You are missing to call the get_results method like this:
<?php
global $wpdb;
$id = 23;
$sql = $wpdb->prepare( "SELECT * FROM tablename WHERE id= %d",$id);
$results = $wpdb->get_results( $sql , ARRAY_A );
?>
The use of the prepare method is a good practice for preparing a SQL query for safe execution (eg. preempt SQL injection), but it is no yet the execution, it returns a sanitized query string, if there is a query to prepare.
It is also good companion for the query method.
After some iterations I finally got it to work!
I understand mySQL does not accept input with a spacing?
How can I insert a WHERE condition for multiple words or a paragraph?
It worked for me using the following script but I had to change the WHERE value into an integer.
<?php
add_shortcode('Initial_Brief', function(){
global $wpdb;
$sql = $wpdb->prepare("Select Value from `P100` WHERE `P100`.`id` = 1 ");
$results = $wpdb->get_results( $sql , ARRAY_A );
foreach ($results as $result) {
$display = implode(", ", $result);
echo $display;
});?>
I have issues with category and subcategory fields.
shortly, I made category like this: literature, and want to make drop down sub menu like this: poetry, novel, non-fiction.
I receive all the categories on the website, but can't get subcategory field at all.
Here is my code:
$category=htmlspecialchars($_REQUEST['category']);
if(isset($category)){
$avt=mysql_query("select * from category order by id asc");
while($category_id=mysql_fetch_array($avt))
{
?>
<li><a href="#"> <k style="font-size:11px;"> <?
echo $category_id['catname'];
} }
?> </k> </a>
<?
$subcategory=htmlspecialchars($_REQUEST['subcategory']);
if(isset($subcategory)){
$sql = mysql_query("SELECT t1.*,t2.* FROM category as t1, subcategory as t2 WHERE t1.id=t2.'$_REQUEST[subcat_id]'");
while($data = mysql_fetch_array($sql))
{ ?>
<ul style="z-index:101;">
<li> <k> <?php echo $data["subcat_name"]; ?> </k></li>
<? } }
?>
And here is the mysql:
category
id
catname
Subcategory
id
subcat_id
subcat_name
That's all. I would be grateful if some can help me to solve this. (I am beginner obviously)
Thank you
Even though you are a beginner, I would suggest you probably heavily retool this. Start with your database connection. mysql_ functions are deprecated (not recommended for use) in the latest v5 of PHP and removed altogether in PHP v7 because they are security risk and are poorly implemented by most. Use PDO or MySQLi instead. I prefer PDO, so I will demonstrate that:
# Create the connection thusly, fill in your own credentials
$con = new \PDO("mysql:host=localhost;dbname=mydatabase", $username, $password);
Next, you should know the difference between isset and empty. In your case, your isset will throw a warning if $_REQUEST['category'] is not set. When you create your own variable, it's guaranteed to be set when you check it because you manually just created it.
This will throw a warning if $_REQUEST['category'] is not set because you assign it before you check it:
$category = htmlspecialchars($_REQUEST['category']);
This WILL NOT throw a warning because you are checking if $_REQUEST['category'] is set yet. If not, assign $category to false by default:
# I like to use a ternary when there are only two options, but you can use if/else
$category = (isset($_REQUEST['category']))? htmlspecialchars(trim($_REQUEST['category'])) : false;
# This part now checks if the value that you created is NOT EMPTY because you
# have just created it, so checking if it is set is illogical
if(!empty($category)):
# Now we use our connection here to query.
# Here we can use query() because we don't have any variables to add into the query,
# so it's safe to use this short version
$avt = $con->query("select * from category order by id asc");
# Same while loop, just use the PDO version of fetching the results
while($category_id = $avt->fetch(\PDO::FETCH_ASSOC)): ?>
<?php
/**
* I'm not sure why you are using a "k" tag, so just combine with "a" tag
* also, though you can use <? as a php open, it's not recommended
* lastly, you have the close tag for "a" outside the loop, that is bad syntax
* since the open is inside the loop
*/
?>
<li><?php echo $category_id['catname'] ?></li>
<?php endwhile ?>
<?php endif ?>
Now that the top part is finished, you have the same issues (plus a couple more) on this second part of the code:
# It's also worth noting here you have set this variable, but you don't actually use it...?
# Secondly, you are checking for "subcategory" here, but in the code below you are injecting "subcat_id"...should they match??
$subcategory = (isset($_REQUEST['subcategory']))? htmlspecialchars(trim($_REQUEST['subcategory'])) : false;
if(!empty($subcategory)):
# Here is where you need to make a detour with your script. What you are doing is unsafe.
# You can not inject that value right into the sql. You need to "prepare", "bind value", and "execute" it
$subcat_id = $_REQUEST['subcat_id'];
# First prepare using ? as placeholders for the value you want to search for
# The naming convention on the "subcat_id" column I assume is actually the
# the parent category? If so, maybe it should be called "parent_id" or "category_id"??
$sql = $con->prepare("SELECT t1.*, t2.* FROM category as t1, subcategory as t2 WHERE t1.id = ? AND t2.subcat_id = ?");
# Now you want to execute for those two question marks (?)
# There are a few ways to prepare and bind parameters, this way is easy
# and you can visually see what we are trying to accomplish
$sql->execute([$subcat_id, $subcat_id]) ?>
<!-- you probably don't want to be looping this (or it's close tag) -->
<ul style="z-index:101;">
<?php
# Same type of thing as your first block of code
while($data = $sql->fetch(\PDO::FETCH_ASSOC)): ?>
<li> <?php echo $data["subcat_name"] ?> </li>
<?php endwhile ?>
<!-- end list -->
</ul>
<?php endif ?>
The final conclusion here is that you have some work to be done before you get to the main problem which is likely your SQL statement and the value you are querying. I would suggest reading up on any of the concepts mentioned that you are not familiar with.
I am a novice to HTML, JavaScript, PHP and pretty much programming in general and I've run into a bit of a problem with a basic shopping cart/e-commerce site I am trying to build.
The main page has a navigation tree in the left frame (before you say "why are you using frames!!!" I know.... My professor for some reason requires us to use outdated techniques in his assignments...). The top right frame contains a product detail which when will show product details when you click on the lowest tier (actual products) of the navbar. When I actually define the product_id in the query I am able to populate the product details table with the correct information. However, when I click on the actual navigation bar links, it doesn't send the product_id to that page for the query.
I'm pretty sure I'm missing something fundamental here, and unfortunately I can't proceed with actually trying to teach myself how to populate the cart until I can get the product details up on the page! Heavy....
Anyway, here is the way I've formatted the links: i.e:
<li>Chocolate Bar
</li>
And here is the php I have on the products page:
<?php
$product_id = $REQUEST['product_id'];
$query_string = "select product_name, unit_quantity, unit_price from products
where (product_id = $product_id)";
$result = mysql_query($query_string,$link);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0 ) {
print "<table border='0'>";
while ($a_row = mysql_fetch_assoc($result) ) {
print "<tr>\n";
print "<td>$a_row[product_name]</td>";
print "<td>$a_row[unit_quantity]</td>";
print "<td>$a_row[unit_price]</td>";
print "</tr>";
}
print "</table>";
}
mysql_close($link)
?>
What am I doing wrong here? I feel like I'm maybe missing some critical PHP on the main page to tell it to send that information over and maybe missing something on the products page to receive it?
Change this
$product_id = $REQUEST['product_id'];
to this
$product_id = $_REQUEST['product_id'];
or this
$product_id = $_GET['product_id'];
You may go through this manual for further information.
Suggestion, unrelated, refrain yourself from using mysql_* functions because they are deprecated and will be discontinued in future.
Try $_GET instead of REQUEST
and try without the ()'s
$query_string = "select product_name, unit_quantity, unit_price from products
where product_id = $product_id";
the issue is in the query, $product_id must be inside another pair of quotes caouse thats the string that gouse to MYsql
$query_string = "select product_name, unit_quantity, unit_price from products
where (product_id = '".product_id."'")";
$result = mysql_query($query_string,$link);
You could indead use REQUEST put you should write it like $_REQUEST. To prevent future errors though you could also use $_GET.
$product_id = $_GET['product_id'];
$query_string = "select product_name, unit_quantity, unit_price from products
where (product_id = '".$product_id."')";
I'm currently pulling the data from MySQL Database with the current code Example 1
function User_Details($uid){
$uid = mysql_real_escape_string($uid);
$query = mysql_query("SELECT uid,password,email,nickname,username,profile_pic,friend_count FROM users WHERE uid='$uid' AND status='1'");
$data = mysql_fetch_array($query);
return $data;
}
I'd like to use this query across multiple PHP pages without having to write a foreach loop for every PHP file.
Currently I have it inside a class called class Wall_Updates { }, and I try to print it with the following code: Example1 : < ?php echo $data['username']; ? >.
The class Wall_Updates is being called on the header which should also include the User_Details, so the only issue is how do I print with just the following PHP example I gave above without the need of a loop.
The class words with single fielded queries such as Example 2 $face = $Wall->Profile_Pic($msg_uid); and if I echo $face it'll show my current Profile_Pic which is a single query.
Example 3 of how I don't want to do as it's very messy.
<?php
if ($uid) {
$updatesarray = $Wall->Updates($uid);
}
if ($updatesarray) {
foreach ($updatesarray as $data) {
$username = $data['username'];
?>
#HTML CODE GOES HERE
<?php } ?>
So I'd like my query to pull multiple fields from users and use it across any page without a foreach.
PS: I'm sorry if it's not making sense, I've been complained a lot for not showing what I've tried and I hope to not get complained about it this time, I appreciate for looking at my question.
you need to issue the "or die" sql command EVERYWHERE otherwise you have no idea why it failed.
http://pastie.org/7897405
you have a column name wrong (look at the last line of the pastie
also, get off of the mysql_ stuff and get into pdo. you should know better chump !
I'm sure my inability to solve this problem steams from a lack of knowledge of some aspect of php but I've been trying to solve it for a month now with no luck. Here is a simplified version of the problem.
In my database I have a members table, a childrens table (the children of each member), and a friend requests table (this contains the friend requests children send to each other).
What I'm attempting to do is display the children of a particular parent using the following while loop....
$query = "SELECT * From children " . <br>
"WHERE parent_member_id = $member_id"; <br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_children = mysql_num_rows($result);<br>
echo $num_children;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
<div>echo $first_name<br>
}
This while loop works perfectly and displays something like this...
1) Kenneth
2) Larry
What I'm attempting to do though is also display the number of friend requests each child has next to their name...like this
Kenneth (2)
Larry (5)
To do this I attempted the following modification to my original while loop...
$query = "SELECT * From children " .<br>
"WHERE parent_member_id = $member_id";<br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_movies = mysql_num_rows($result);<br>
echo $num_movies;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
echo $first_name; include('counting_friend_requests.php') ;
}
In this version the included script looks like this...
$query = "SELECT <br>children.age,children.child_id,children.functioning_level,children.gender,children.parent_member_id,children.photo, children.first_name,friend_requests.request_id " .
"FROM children, friend_requests " .
"WHERE children.child_id = friend_requests.friend_two " .
"AND friend_requests.friend_one = $child_id"; <br>
$result = mysql_query($query)<br>
or die(mysql_error());<br>
$count = mysql_num_rows($result);<br>
if ($count==0)<br>
{<br>
$color = "";<br>
}<br>
else<br>
{<br>
$color = "red";<br>
}<br>
echo span style='color:$color' ;<br>
echo $count;<br>
echo /span;<br>
Again this while loop begins to work but the included file causes the loop to stop after the first record is returned and produces the following output...
Kenneth (2)
So my question is, is there a way to display my desired results without interrupting
the while loop? I'd appreciate it if anyone could even point me in the right direction!!
Avoid performing sub queries in code like the plague, because it will drag your database engine down as the number of records increase; think <members> + 1 queries.
You can create the query like so to directly get the result you need (untested):
SELECT child_id, first_name, COUNT(friend_two) AS nr_of_requests
From children
LEFT JOIN friend_requests ON friend_one = child_id OR friend_two = child_id
WHERE parent_member_id = $member_id
GROUP BY child_id, first_name;
It joins the children table records with friend_requests based on either friend column; it then groups based on the child_id to make the count() work.
You don't need to include the php file everytime you loop. Try creating a Person class that has a method getFriendRequestCount(). This method can all the database. This also means you can create methods like getGriendRequests() which could return an array of the friend requests, names etc. Then you could use count($myPerson->getFriendRequests()) to get the number. Thousands of options!
A great place to start, http://php.net/manual/en/language.oop5.php
Another example of a simple class, http://edrackham.com/php/php-class-tutorial/
Eg.
include ('class.Person.php');
while(loop through members)
$p = new Person(member_id)
echo $p->getName()
echo $p->getFriendRequestCount()
foreach($p->getFriendRequests as $fr)
echo $fr['Name']
In your Person class you want to have a constructor that grabs the member from the database and saves it into a private variable. That variable can then be accessed by your functions to proform SQL queries on that member.
Just to clarify whats happening here.
"include" processing is done when the script is parsed. Essentially its just copying the text from the include file into the current file. After this is done the logic is then parsed.
You should keep any include statements separate from you main logic. In most cases the "include"d code will contain definitions for one or more functions. You can then call these functions from the main body of your program at the appropriate place.