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}");
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 know I'm probably doing this in a round about fashion but I don't understand why it wont work or a better way to just retrieve ONLY THE STRING VALUES in an array so that I can move them to a different table. I thought I could iterate through the array list and output only the strings in the array but it is not working :(
//database config and wpdb access code...
<?php
$cbposttitles = $wpdb->get_col('SELECT post_title FROM wp_posts' );
$countofposttitles = count($cbposttitles);
echo "count of post tiles . $countofposttitles"; //counts correctly
?>
<br>
<?php
for ($x = 0; $x < $countofposttitles; $x++) {
$individualpost = $wpdb->get_var('SELECT post_content FROM wp_posts WHERE ID =
[$x]');
echo $individualpost; // does't work
}
?>
$countofposttitles contains nothing but the number of posts/titles. This you have no use for in your piece code. You probably try to select some kind of ids from your first query and look for each of these in your second. However, this is very inefficient since you're making a lot of unnecessary database requests.
Which strings and/or values to you actually want and what is the purpose? You're using two queries for the same table, either you want both fields or just one? If you want both fields then just select both in one query:
SELECT post_title, post_content FROM wp_posts
I've been writing some code that essentially collects information based on schools and the user search input. Once the information is pulled up, I also query a database containing users to show how many are signed up at each school, and then another database containing files showing how many files have been uploaded from each school.
I imagine this would require a three tiered loop? If I query the school database and then the student database in succession it works great (Every school will have the appropriate number of students signed up displayed). However the problem is with the files. If I add in the file query, it will only show the first two results of the schools.
This leads me to believe that the file database query isn't correct and after testing a two tiered loop (this time will files instead of students) it appears to be the case. So, what am I doing wrong with the file database code? I copied it directly from the student database code so I haven't a clue why this one won't work. Here is the code that works:
mysql_select_db($database_geographic, $geographic);
$query_school = "SELECT * FROM geographic.school WHERE countryid='$countryid' AND stateid='$stateid' ORDER BY school_name ASC";
$school = mysql_query($query_school, $geographic) or die(mysql_error());
$totalRows_schools = mysql_num_rows($schools);
while ($row_school = mysql_fetch_assoc($school)) {
echo $row_school['school_name'];
echo $row_school['city_name'];
echo $row_school['state_name'];
echo $row_school['schoolid'];
$schoolid = $row_school['schoolid'];
mysql_select_db($database_user_information, $user_information);
$query_users = "SELECT COUNT(*) AS studentcount FROM users WHERE school_name= '$schoolid'";
$users = mysql_query($query_users, $user_information) or die(mysql_error());
while ($row_users = mysql_fetch_assoc($users)) {
echo $row_users['studentcount']; }
But if I throw in this third files loop statement it will not work.
mysql_select_db($database_files, $files);
$query_files = "SELECT COUNT(*) AS filecount FROM file_data WHERE school_id= '$schoolid'";
$files = mysql_query($query_files, $files) or die(mysql_error());
while ($row_files = mysql_fetch_assoc($files)) {
echo $row_files['filecount']; }
}
If I use the file query in place of the student query it will not work either. The problem must be with the file query but I can't figure it out. Any help would be awesome! Thanks!
Say I have a database table titled "people" and under the column "names", I have "Bill", "Karen", and "Ted".
In my php file, I want to use just one template and using those rows, have a seperate page for each name (like "myfile.php?name=Bill"). From what I understand, I have to use GET, but I'm pretty still confused and inexperienced with that, so how would I go about obtaining my goal here?
If you want to make a page based of a name in the get variable use this.
This basicly takes the name and takes it to the database and selects all field pretaining to that name, then you echo out the varibles and place them where you want a such.
<?php
$name = $_GET["name"];//gets name value from your url that you supplied in your post
$con=mysqli_connect("127.0.0.1","db-username","db-pass","db-name");
mysqli_real_escape_string($con,$name);
$sql = mysqli_fetch_assoc(mysqli_query($con,"SELECT * FROM people WHERE names='$name'"));
$id = $sql['id'];//id would be a field in the people table
$age = $sql['age'];//age would be a field in the people table
echo '<h1>'.$name.'</h1>';
echo '<p>'. $id .'<br/>'. $ age .'</p>';
?>
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.