The code below returns nothing, but if I remove this line:
'desc' => $row['DESC'],
from the function it works fine.
DESC Is a valid column in the database and when I run the full query in phpmyadmin, it returns the desired result.
I am not sure why this line
'desc' => $row['DESC'],
breaks the return of the result.
=======
After more investigating I can see the JSON output has the same issue.
Altering the column name (since DESC is a keyword) and reflecting the changes in the query has no effect.
========
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, DESC, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['DESC'],
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved word in SQL. If you want to use it as a column, you should protect it with forward quotes:
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, `DESC` AS D, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['D'], // Using the alias, just in case
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved Keyword do something like
SELECT DISTINCT NAME, DESC as yourVar, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC
and then like that
'desc' => $row['yourVar'],
$stmt = $db1->query("SELECT DISTINCT `NAME`, `DESC`, `CLASSCODE` FROM `tbl_subjects` WHERE `VISIBLE` = 1 ORDER BY `NAME` ASC");
there was syntax error because desc is reserved keyword, you have to use quotes, the best habbit is quote each column and each table name
Thank you all for your answers - I found the problem and what broke the script was that my strings in my JSON values had several - in them.
It took me a while to find it :-)
Related
Creating an array (which I want to encode to JSON) from a MySql select query, but one of the query columns has free text entered by users. I don't want special characters (or 'n/' formatting) in this column preventing the array from populating correctly. Not all rows are being displayed by the current statement and 'n/' etc characters are being included:
echo json_encode($data); //not sure this is in the right part of my code
I've used the below code successfully before but not in an array:
echo nl2br($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8");
My PHP code:
if(!empty($_POST['msg']))
{
$userid = session_id();
$searchStr = get_post($con,'msg');
$aKeyword = explode(" ", $searchStr);
$aKeyword = array_filter($aKeyword); // Remove empty values
$stmt = $con->prepare(
'SELECT
a.ID, a.MessageText, a.cntLikes, IFNULL(b.Type,0) as Type
FROM
(
SELECT m.ID, m.MessageText,count(l.Id) as cntLikes
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE MessageText REGEXP ?
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc
)a
LEFT OUTER JOIN
(
SELECT postId, COUNT(*) as type
FROM likes
WHERE userid = ?
GROUP BY postId
)b
on a.Id = b.PostId'
);
$regexString = implode('|', $aKeyword);
$stmt->bind_param('ss',$regexString, $userId);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if(mysqli_num_rows($result) > 0) {
While($row = $result->fetch_assoc()) {
$data = $row;
echo json_encode($data);
}
}
}
What solved the issue was amending:
$data = $row;
to:
$data[] = array ( 'ID' => $row['ID'], 'UserID' => $row['UserID'], 'MessageText' => nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") ), 'cntLikes' => $row['cntLikes'], 'Type' => $row['Type'] );
The database column that was stopping the array from pulling back was 'MessageText'. This column had originally come from an Excel spreadsheet where the data was very dirty.
Using
nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8"))
resolved the issue.
if ($stmt - > execute()) {
if ($stmt - > rowCount() > 0) {
$menu_id = array();
while ($selected_row = $stmt - > fetch(PDO::FETCH_ASSOC)) {
$menu_id[] = array('menuid' => $selected_row['menulist_id'], );
}
$stmt = $dbh - > prepare("SELECT * FROM menulist_tbl WHERE menulist_id = :menuid AND menu_displayorder <= :value");
$menu_name = array();
$input = array_map("unserialize", array_unique(array_map("serialize", $menu_id)));
//print_r($menu_id);
//print_r($input);
foreach($input as $row) {
$stmt - > execute(array(':menuid' => $row['menuid'], ':value' => '10000'));
//while ($selected_row =$stmt->fetch(PDO::FETCH_COLUMN, 0)){
while ($selected_row = $stmt - > fetch(PDO::FETCH_ASSOC)) {
$menu_name[] = array('displayorder' => $selected_row['menu_displayorder'], 'menuname' => $selected_row['menu_name'], 'menuurl' => $selected_row['menu_url'], 'menuflag' => $selected_row['menu_flag'], 'menuid' => $selected_row['menulist_id']);
}
}
array_multisort($menu_name);
//print_r($menu_name);
return $menu_name;
}
}
This is how i get menu from database this code will do the following:
From result of another query it will store in an array the menulist_id then I will use this menulist_id to query the menu table for menu name that has a display order of less 10000 , I have this parameter of less than 10000 because i can hide menu from the list of menu without deleting them so I want to show them again I just reduce their display order and they can be seen again. But why is my display order parameter not working even if i have a display order of 10011 the menu is still showing. Any idea is appreciated
FYI
the column menu_displayorder is varchar.
For a varchar you will want to CAST as a numerical data type that can controlled better with >= try this:
AND CAST(menu_displayorder AS UNSIGNED) <= :value
I want to retrieve the data from db using PHP
$device_owner_resultset=mysqli_query($con, "SELECT * FROM `device_owner_details` WHERE `deviceId` =$device_details_data_id");
$device_owner_resultset_data = mysqli_fetch_array($device_owner_resultset);
$owner_deviceid = $device_owner_resultset_data['deviceId'];
$owner_name = $device_owner_resultset_data['name'];
$name_fetch_rows = mysqli_fetch_row($device_owner_resultset);
$device_realtime_resultset=mysqli_query($con, "SELECT * FROM `device_realtime_stats` WHERE `deviceId` = $owner_deviceid LIMIT $start_from , $limit");
$rows_fetch = mysqli_fetch_row($device_realtime_resultset);
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
for($i=1;$i<=20;$i++)
{
$details =array('name' => $name_fetch_rows[$i]-> name, 'latitude' => $rows_fetch[$i] -> currentLatitude, 'longitude' => $rows_fetch[$i] -> currentLongitude);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}
Here i have an parse error, what is the mistake from my coding , i think error is in mysqli_fetch_rows and its calling array
You are not using mysqli_fetch_row($result) correctly. The function mysqli_fetch_row($result) does not return all the row data. It returns an array of a single row as an enumerated array. Try this code using this code instead:
// Now only selects name column and added LIMIT 1 to MySQL query for efficiency
$device_owner_resultset = mysqli_query($con, "SELECT name FROM `device_owner_details` WHERE `deviceId` = $device_details_data_id LIMIT 1");
// Now using mysqli_fetch_assoc($result)
// instead of mysqli_fetch_array($result) for clarity
$device_owner_resultset_data = mysqli_fetch_assoc($device_owner_resultset);
// Got rid of $owner_deviceid because it should be the same as $device_details_data_id
$owner_name = $device_owner_resultset_data['name'];
// Got rid of $name_fetch_rows because it is redundant with $device_owner_resultset_data
// Query now specifies which columns it selects for clarity and efficiency
$device_realtime_resultset = mysqli_query($con, "SELECT currentLatitude, currentLongitude FROM `device_realtime_stats` WHERE `deviceId` = $device_details_data_id LIMIT $start_from, $limit");
if ($total_pages <= $page && $total_pages > 0) {
$device_details=array('devices'=> array());
// This loops through all the rows from the query
while ($row = mysqli_fetch_assoc($device_realtime_resultset)) {
// $row is an associative array where the column name is
// mapped to the column value.
// The owner name should remain the same because there is
// only one owner.
$details = array('name' => $owner_name,
'latitude' => $row["currentLatitude"],
'longitude' => $row["currentLongitude"]
);
array_push($device_details['devices'], $details);
}
$response = json_encode($device_details);
echo $response;
}
If the columns of the device_realtime_stats table are not named currentLatitude and currentLongitude make sure they are renamed.
$mysql_all_resultset = mysqli_query($con, " SELECT dot.name, drs.currentLatitude, drs.currentLongitude FROM device_details dt, device_owner_details dot, device_realtime_stats drs WHERE dt.vendorId=$vendor_id AND dot.deviceId=dt.id AND drs.deviceId= dot.deviceId LIMIT $start_from, $limit ");
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
while ($rows_fetch = mysqli_fetch_assoc($mysql_all_resultset))
{
$details =array('name' => $rows_fetch['name'], 'latitude' => $rows_fetch['currentLatitude'], 'longitude' => $rows_fetch['currentLongitude']);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}
Im a "noob" in smarty. I need to execute following code in one of my .tpl files:
<? // SELECT sql query
$sql = "SELECT 'id' , 'title' FROM `forum_posts` WHERE bid = '1' ORDER BY 'date' DESC LIMIT 4";
// perform the query and store the result
$result = query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
echo '<tr>
<td>'. $row['title']. ' </td>
</tr> ';
}
}
else {
echo 'No news';
}
?>
I've been trying for 3 hours now, surfing all over the web but without success.
Help please!
You are using quotes instead of backtick for column name, simply change them to avoid the error
SELECT `id` , `title` FROM `forum_posts` WHERE `bid` = '1' ORDER BY `date` DESC LIMIT 4";
require('../libs/SmartySQL.class.php');
$smarty = new SmartySQL( array('pdo_dsn' => 'mysql:dbname=db_name;host=localhost',
'pdo_username' => 'username',
'pdo_password' => 'password',
'pdo_driver_options' => array() ) );
$smarty->display('index.tpl');
I have something like that in my mySQL database:
(User 734 have many informations : biography, name, phone, mail ...)
I want to get an array (in PHP) with grouped datas :
array(
[734]=>
object {
[155] => string "Dominique",
[4] => int(047682037),
[1] => string "Dominique B"
},
[735]=>
object {
[155] => string "Other",
[4] => int(0123456789),
[1] => string "Other B"
}
)
not only for 734 user but for each user. With a simple query I get everything but not in the good order. Can I make it in SQL or I maybe need to rearrange datas in PHP next ?
What is the sql query to get, for each user_id, all the related datas ?
I can't change the database structure (WP and buddypress)
I can't use native WP functions (because getting datas from another site)
SELECT * FROM (whatever your table name is)
WHERE user_id = (whatever user id you're interested in getting data for)
Solution using ORDER BY :
$users = array();
$current_user = null;
$result = $mysqli->query("SELECT user_id, field_id, value FROM `TABLE_NAME` ORDER BY user_id, field_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
if ($current_user != $row['user_id']) {
$current_user = $row['user_id'];
$users[$row['user_id']] = array();
}
$users[$row['user_id']][$row['field_id']] = $row['value'];
}
EDIT :
There is another solution using GROUP BY and GROUP_CONCAT :
$users = array();
$result = $mysqli->query("SELECT user_id, GROUP_CONCAT(field_id SEPARATOR '|') as fields, GROUP_CONCAT(value SEPARATOR '|') as values FROM `TABLE_NAME` GROUP BY user_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
$fields = explode('|', $row['fields']);
$values = explode('|', $row['values']);
$users[$row['user_id']] = array();
// Problem id you have your field ids and your values in separate arrays, not sure what you want to do with them
}
$result = mysqli_query($con, "SELECT * FROM table_name WHERE user_id = 734");
Or if you arent using mysqli:
$result = mysql_query("SELECT * FROM table_name WHERE user_id = 734");
If you are using the PDO library you could check the PDO::FETCH_GROUP attribute.
http://php.net/manual/en/pdostatement.fetchall.php
fetch_style:
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
$stmt = $this->_mysqli->prepare('SELECT user_id,field_id,value FROM WHERE user_id = ?');
$stmt->bind_param('i', $user_id );
$stmt->execute();
$stmt->bind_result($user_id, $field_id, $value);
while($stmt->fetch())
{
$data[$user_id][$field_id] = $value;
}