MySQL subquery not going into Array in PHP - mysql

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");

Related

Get content from another DB in wordpress

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

how to display count() sql function using php

how to display count() sql function using php
$results = "SELECT count(votesnumber) FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['votesnumber'];
} else {
echo "error";
}
i want to display the results of sql count() function using php. am counting specific columns WHERE ID = "some value" in phpmyadmin its working but with php its giving me headache . any ideas on how to solve this?
Try this:
$results = "SELECT count(votesnumber) AS VoteNum FROM `votes` WHERE `candidate_id` = '$candidate_id'";
$queryresults = mysqli_query($connect, $results);
if($queryresults) {
$rowresults = mysqli_fetch_assoc($queryresults);
echo $rowresults['VoteNum'];
} else {
echo "error";
}
First, if you want to refer to the column name by a reference, then you need to give it a better name using an alias:
SELECT COUNT(votesnumber) as votesnumber
ROM `votes`
WHERE `candidate_id` = '$candidate_id';
Second, you should not be munging query strings with parameter values. Instead of '$candidate_id', learn to use parameters. This prevents unexpected syntax errors and SQL injection accounts.
Third, if votesnumber is actually a number of votes, then you probably want SUM() rather than COUNT().
You need to add "AS" instruction to your SQL if you want to get this data as a specific index from array (like $rowresults['votes']):
$results = "SELECT count(votesnumber) AS votes FROM `votes` WHERE `candidate_id` = '$candidate_id'";
Remember that you can always print_r() (for arrays) or var_dump() your variable to check if it contains data you want to have.

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;

JSON validator validates the JSON but my left hand tags are not appearing

i am developing an iOS app and this app fetches data using JSON from mysql database. i have configured the json properly so far. right hand $outputs are ok and json validator validated the json formatting is completely ok. but my left hand tags are not appearing some how. here i m providing the code what i did. For this app publishing is on hold for long time.
//fetch data from current month table
$q = mysql_query("SELECT * FROM $monthyear where news_date = '$date'");
if (!$q) {
die('Invalid query executed: ' . mysql_error());
}
while($e=mysql_fetch_row($q)){
$output[]=$e;
$responce[$e]['news_id'] = $output['news_id'];
$responce[$e]['news_title'] = $output['news_title'];
$responce[$e]['news_reporter'] = $output['news_reporter'];
$responce[$e]['news_details'] = $output['news_details'];
$responce[$e]['photo'] = $output['photo'];
$responce[$e]['path'] = 'admin/'.str_replace('\\','',$output['path']);
$responce[$e]['menu_id'] = $output['menu_id'];
$responce[$e]['menu_type'] = $output['menu_type'];
$responce[$e]['news_publish_status'] = $output['news_publish_status'];
$responce[$e]['news_order'] = $output['news_order'];
$responce[$e]['news_date'] = $output['news_date'];
$responce[$e]['news_time'] = $output['news_time'];
$responce[$e]['added_by'] = $output['added_by'];
$responce[$e]['directory'] = $output['directory'];
$responce[$e]['read_number'] = $output['read_number'];
$responce[$e]['comment_number'] = $output['comment_number'];
$responce[$e]['news_comment_table_name'] = $output['news_comment_table_name'];
}
echo(json_encode($output));
I am not getting any way to show left hand tags though it exists in the script. can any one help me on this by guiding or giving an example from existing source code after modifications. TIA
Ishtiaque
You are using $e which is an array as an array key in $response[$e], and this is not allowed in PHP:
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
I think you want to use the ID as a key.

How could a query fail to insert data into mysql that is retrieved from WEB?

I need to insert some data into mysql. I am not sure if I need to check the inputs OR format/strip them before they could be inserted into database fields as results returned from web may contain characters that mysql do not accept(I think). I have trouble with inserting tweets into mysql table. The type of field is varchar. This is insert statement in php script:
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status)
{
$t = $status->content;
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error());}
}
Yes, it's very important to escape all values before using them in an SQL command.
$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status) {
$t = mysql_real_escape_string($status->content);
$query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
mysql_query($query);
if( !mysql_query($query, $dbh) ) {
die('error:' .mysql_error());
}
}
Also, other possible issues with your query:
If the id field is auto_increment'ing, you don't need it in the field or value list.
I may be missing something, but why are you using the string 'ID' for the msg_id field?
As for help troubleshooting this, I'd recommend just appending all of the $query strings to a log file for later inspection. Then, if problems aren't readily apparent, you can just manually try to run the command on the database (ie: maybe via PhpMyAdmin) and check out any error codes from there.