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;
});?>
Related
The page display all results, now I want to filter results and how many results per page. To do this the visitor use a simple html GET form to select the filter.
Now I get the GET form and try to filter the results
<?php
$order_by = mysqli_real_escape_string($database,$_GET['order_by']);
$order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';
?>
OK now we get the filter and try to get results from MySQL like this
$set_order=mysqli_query($database,"SELECT * FROM `products` order by `$order` ASC");}
But I get error in the line:
$order = if(empty($order_by)){echo 'manufacturer';}else{echo '$order_by';
Cannot find a way to do this ... Any idea?
using single quotes around a variable will not work - but why not assign the variable and then echo it back?
$order = empty($order_by) ? 'manufacturer' : $order_by;
echo $order;
if however this is to be used in the sql query you do not need to echo it.
After a short 8r break for sleep you have an answer but I'll post this here too.
$order = empty($order_by) ? 'manufacturer' : $order_by;
$sql="select * from `products` order by `{$order}` asc;";
$set_order=mysqli_query( $database, $sql );
if( $set_order ){
/* process recordset */
}
First, set a default value for order by.
$order = 'manufacturer';
Next, if the user has provided something else, replace the default value with that.
if (!empty($_GET['order_by'])) {
$order = mysqli_real_escape_string($database, $_GET['order_by']);
}
Then you can use whatever it ends up being in your query.
$set_order = mysqli_query($database, "SELECT * FROM `products` order by `$order` ASC");
It is definitely good that you're using mysqli_real_escape_string here, but I would recommend checking the user input against a list of acceptable column names to mitigate the SQL injection risk.
try this:
if(empty($order_by)){$order = 'manufacturer';}else{$order = $order_by;}
I have created a table called ccc_campaigns in my database and I am retrieving the data with the following statement:
global $wpdb;
$campaign_list = $wpdb->get_results(
'SELECT *
FROM ccc_campaigns
ORDER BY id DESC');
This works as expected on my local and on one of my servers, the data is displayed doing:
foreach ($campaign_list as $campaign)
But in the server where this wordpress is supposed to be, the query comes back empty. I can't understand or find a reason why it is failing on that server.
Any ideas?
Thank you so much
Make sure the database prefix are the same.
EDIT: I guess you are building some kind of plugin, so just to make sure, db prefix is not causing any errors, use this function instead.
function getCampaignResults(){
global $wpdb;
$table_name = $wpdb->prefix . "campaigns";
$active_rows = $wpdb->get_results(
"SELECT * FROM {$table_name}"
);
foreach ($active_rows as $active_row){
echo $active_row->the_title;
}
}
I'm trying to figure out why my query isn't running, and if it is; why isn't it returning any info. I'm running this query on wordpress multisite based on a plugging that goes through all network sites and retrieves all posts in the main site, that part is working fine. I created a bit of code to merge two variables into one variable to create a table name, if I echo that variable it displays the table name correctly, but when i insert the same variable in the query noting happens even dough the table already exists in the DB. the code is below:
// Switch to the blog
switch_to_blog($all_blogkeys[$field->guid]);
global $wpdb;
$prefix = $wpdb->prefix; //get current site table prefix
$table = 'rex_listings'; // name to attach to prefix
$tablename = $prefix.''.$table; // combine prefix and name
//start the query and echo results
$result = $wpdb->get_results('SELECT price, bedrooms, baths, floor_space, formatted_address FROM $tablename');
foreach($result as $row) {
echo 'Price: '.$row->price.', Bedrooms: '.$row->bedrooms.', Baths: '.$row->baths.', Floor Space: '.$row->floor_space.', Address: '.$row->formatted_address.',<br/>';}
Thanks in advance.
You need to use double quotes around the query and curly brackets around the variable, like so:
$result = $wpdb->get_results("SELECT price, bedrooms, baths, floor_space, formatted_address FROM {$tablename}");
//conn to DB
echo $_POST['text'];
$filter = $_POST['text'];
$sql = "SELECT DISTINCT * FROM contents
WHERE
MATCH(content,title) AGAINST ('$filter')
";
$mksql=mysql_query($sql);
while($row = mysql_fetch_assoc($mksql)) {
echo $row['title']."<br />";
}
I send POST request to another page with the above code.
It echoes me what I wrote in the input field but it doesn't output any result.
When I run the query in phpmyadmin in works and outputs me 1 result.
Where's the problem?
Try this :
$sql = "SELECT DISTINCT * FROM contents
WHERE MATCH(content,title) AGAINST ('$filter' IN BOOLEAN MODE ) ";
Before query any fulltext search you must create mysql fulltext indexing.
Execute this query in phpmyadmin.
ALTER TABLE contents ADD FULLTEXT(content, title);
may be there is problem in the post data which is not matching with full text search. you can use mysql_escape_string(), htmlspecialchars() functions for the post data you are using for query. These functions will help avoiding html tags,quotes,etc. you can print the generated sql and run that query in phpmyadmin. and of course create mysql fulltext indexing for the field you are searching.
I am very new to php/mysql and this is causing me to loose hairs, I am trying to build a multi level site navigation. In this part of my script I am readying the sub and parent categories coming from a form for insertion into the database:
// get child categories
$catFields = $_POST['categories'];
if (is_array($catFields)) {
$categories = $categories;
for ($i=0; $i<count($catFields); $i++) {
$categories = $categories . $catFields[$i];
}
}
// get parent category
$select = mysql_query ("SELECT parent FROM categories WHERE id = $categories");
while ($return = mysql_fetch_assoc($select)) {
$parentId = $return['parent'];
}
The first part of my script works fine, it grabs all the categories that the user has chosen to assign a post by checking the checkboxes in a form and readies it for insertion into the database.
But the second part does not work and I can't understand why. I am trying to match a category with a parent that is stored in it's own table, but it returns nothing even though the categories all have parents. Can anyone tell me why this is?
p.s. The $categories variable contains the sub category id.
I can see a few bugs:
$categories = $categories;
should be
$categories = '';
Since there will be more than on categories you'll have to use the MySQL in clause as:
SELECT parent FROM categories WHERE id in ($categories)
for this to happen you'll have to make categories a comma separated list if ids by altering your for loop as:
for ($i=0; $i<count($catFields); $i++)
$categories .= "$catFields[$i],"; // append 'id,' to existing list.
trim($categories,','); // remove any trailing commas.
$categories seems like it would be a string with more than one value in it, which the SQL engine you're using isn't going to be able to use with just an = where condition. You probably need to change it so that your SQL looks something like WHERE id IN (1,2,3) where 1, 2, 3 etc are your id's that you want to match.
AFAIK, $_POST is an array. Is $_POST['categories'] the data from a multi select html form element?
What kind of data are you sending in $_POST['categories']? How do you expect that to be an array? If you are encoding the data into an array like structure before submitting it to your PHP script, you may have to manually insert it into an array.
Use
$select = mysql_query ("SELECT parent FROM categories WHERE id IN (" . implode(",", $array) . ")");
And don't forget mysql_real_escape_string() in combination with quotes ' in your query, your corrent code is prone to SQL injection. Prepared statements (PDO or MySQLi) will to the trick as well.
But don't trust userinput!