Get content from another DB in wordpress - mysql

I have found out how to make a page for WordPress, where I can write PHP code into.
However, I can not figure out how to retrieve content from another database.
I have found the connect code:
$wpdb2 = new wpdb($dbname, $dbpass, $dbuname, $dbhost);
but I cannot figure out how to retrieve content from the database.
Can someone give an example?
If, for example, have this query
SELECT number
FROM qr_statistic
WHERE date = '$today'

please see this:
wpdb::get_results( string $query = null, string $output = OBJECT )
now you can write your query:
$result = $wpdb->get_results("SELECT number FROM $wpdb->qr_statistic WHERE WHERE date = '$today'");
also see this link

Related

Wordpress - How to write simple query on wordpress ?

I am a newbie and currently learning wordpress , i am struggling to write a query in wordpress. I have written it something like this but seesm like its coming null.
$querystr = "SELECT *
FROM $wpdb->seeker_saved_mark_job ";
$movie_names = $wpdb->get_results($querystr);
var_dump($movies_names);
The seeker_saved_mark_job is placed in meta table. I want to get all the results from this table, and they do exist but Its coming null
Try below query
global $wpdb;
$querystr = "SELECT * FROM ".$wpdb->base_prefix."postmeta WHERE `meta_key`='seeker_saved_mark_job'";
$movie_names = $wpdb->get_results($querystr);
var_dump($movies_names);

In CakePHP 3.x how can I count the number of rows in a MySql table?

I have a MYSQL table called 'devices'. I've successfully done the bin/cake bake all. In fact I have the auto-built DevicesController.php fully working. But I can't figure out how to count the rows in a table. I've tried:
$conn = ConnectionManager::get('default');
$numRows = $conn->execute('select count(*) from devices');
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->query('select count(*) from devices'); // both like this
$numRows = $this->Devices->query('select count(*) from devices')->execute(); // and like this
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->find('count');
Going thru mysql_query() isn't really a good idea because I have all the access info already setup in app.php for CakePHP to use. I tried something else using AnyModel that didn't work.
The former 2 attempts return a Cake\Database\Statement\MysqlStatement not an integer with the number of rows in the table. I've consulted this answer and this answer and read the CakePHP docs. Nothing seems to tell me how to count up a table nor how to execute a raw My SQL command string and then access the result.
TableRegistry::get('DeviceSetups')->find()->count();
See http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#getting-a-count-of-results.
If you want to count in table then it should be like below.
$count = $this->find()->count();
echo $count;

Placing PHP variable inside SQL

I am trying to send city from a page to another and then show items from database where city is the mentioned city but this code does not return any results. Please guide. I am sure everything else is fine with the code.
$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=$city";
// strip tags from the input
$city = strip_tags($_POST["city"]);
// escape the input to prevent sql injection (assuming you are using mysqli() as your connection method...)
$city = mysqli_real_escape_string($city);
// your query does not work because you need to put strings inside single quotes
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";
Actually, you're not even executing the request on your mysql server, but if you are using PDO (what you SHOULD do), just do something like this:
<?php
$bdd = new PDO(etc);
$req = $bdd->prepare("SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=?");
$req->execute(array($_POST['city']));
print_r($req->fetchAll());
?>
And here you go, $req->fetchAll() will return you an array with each element returned by your request, and the best part is that prepare will prevent you from every SQLi
Edit: You can use short syntax for array [$_POST['city']] or old and complete syntax: array($_POST['city'])

MySQL subquery not going into Array in PHP

I have the following PHP API which runs a MySQL query, when;
$sql = "select article_id, title, summary, image_url from articles limit 20";
I get the following result;
http://ec2-54-152-162-157.compute-1.amazonaws.com/list_view.php?user_id=1
the above is what I want the format of my output to look.
However when I change the $sql to below I get a blank screen;
$user_id = $_GET["user_id"];
$sql = "
select article_id, title, summary, image_url
from articles
where article_id in
(
select max(article_id) as last_article_id
from articles as a
join media_sources as ms
on a.rss_source_id = ms.media_source_id
where article_id not in
(
select article_id
from responses
where (activity_id = 1 and response = -1 and user_id = '1')
or (activity_id = 2 and user_id = '1')
)
group by category
) limit 20;"
$db = new mysqli("remotehost", "user", "password", "db_name");
$results = $db->query($sql);
$articles["items"] = array();
while($article = $results->fetch_assoc()){
$item = array ();
$item["article_id"] = $article['article_id'];
$item["article_title"] = $article['title'];
$item["article_summary"] = $article['summary'];
$item["article_image"] = $article['image_url'];
array_push($articles["items"], $item);
//echo json_encode($item);
}
echo json_encode($articles);
I've uncommented echo json_encode($item) in the 3rd from the bottom line of code; and put it in the below API. So there is data but I just can't get into the format I need.
http://ec2-54-152-162-157.compute-1.amazonaws.com/list_view2.php?user_id=1
**********************************EDIT******************************************
json_last_error_msg() returns:
Malformed UTF-8 characters, possibly incorrectly encoded.
So I guess there are characters that can not be encoded in Json, I will have to investigate and strip them out. but still not sure why this one works as it is the same data getting encoded;
echo json_encode($item);
If its working from MySQL console then the issue has to most likely be the credentials that the PHP script uses to connect (maybe it can't access something). Is it the same user? does the php user have permissions to create temporary tables and access all the data needed?
Or perhaps it takes to long and is error'ing out. Which command are you using for the php? Try echoing the error that you are getting back or checking the logs. If its failing it would tell you why it failed.
If its php i'd think its either the mysql user permissions, the php max_execution setting, php max memory
Added this line fixed it;
mysqli_set_charset($db, "utf8");

json encode error when adding a new column in sql

I have a query:
"SELECT Time, Date, Name, Email FROM table"
It converts the results to json to be passed via ajax, the problem is I want a new column in the sql, so I add it to the query:
"SELECT Time, Date, Name, Email, Address FROM table"
now the json encode does not work, I have tried changing data types and using UTF-8 however this did not work, none of the others are using UTF-8 but still work anyway, Thanks.
This is my code to encode to json which does work until I add the new collumn from sql
if ($result = $mysqli->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
Solved
The problem was the last column i was trying to get was called "Show" for some reason sql does not like this, i renamed this column to "lol" (temporary) and it works!