PHP allow special characters from MySQL query column in Array - php

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.

Related

Return JSON with id in front

How do I pull out the id in front of each JSON return object from my API?
Current:
{
"1516":{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
}
How do I want to leave:
[
{
"id":"1516",
"firstname":"Aluno",
"lastname":"Teste",
"email":"teste#gmail.com",
"dlastaccess":"28-10-2016",
"coursename":"Curso Demonstra\u00e7\u00e3o"
}
]
I'm trying to do this because my checklist-model does not work the way the JSON return comes, so I can not check all the checkboxes.
API:
This does the job:
$json = '{"1516":{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}}';
$values = json_decode($json, true);
$values = array_values($values);
echo json_encode($values);
returns:
[{"id":"1516","firstname":"Aluno","lastname":"Teste","email":"teste#gmail.com","dlastaccess":"28-10-2016","coursename":"Curso Demonstra\u00e7\u00e3o"}]
I guess your $result is an array (or object) of this type:
$result[id] = array(sql retrieved);
Because sql returns you a list of results, even if the result is unique. Imagine that your query returned two results, how could you separate them?
Try:
echo json_encode($result[$cursoid])
or
echo json_encode($result->$cursoid)
$cursoid = $_GET['idcurso'];
$sql = 'SELECT
user2.id AS ID,
user2.firstname AS Firstname,
user2.lastname AS Lastname,
user2.email AS Email,
IF (user2.lastaccess = 0,"nunca",
DATE_FORMAT(FROM_UNIXTIME(user2.1astaccess),"%d-96m-W")) AS dLastAccess ,c.fullname AS Coursename
FROM mdl_user_enrolments AS ue
JOIN mdl_enrol AS e ON e.id = ue.enrolid
JOIN mdl_course AS c ON c.id = e.courseid
JOIN mdl_user AS user2 ON user2 .id = ue.userid
WHERE (SELECT timeaccess FROM mdl_user_lastaccess WHERE userid=user2.id AND courseid=c.id) IS NULL and c.id = ?';
$params = array($cursoid);
$result = $DB->get_records_sql($sql, $params);
echo json_encode(array_values($result)); // You can easily access array values without their keys by array_values(array $param) function
Use array_values, default php function
$values = $DB->get_records_sql( $sql, $params );
$result = array_values( $values );
return json_encode($result);

How to Get another value in another table using a dynamic call

I currently have this query with an array that outputs the variables within using a dynamic input in my form (term), this creates a Dynamic Search with auto complete to fill in all of the details for a product.
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
//$row_array['category_id'] = $row ['category_id'];
$row_array['product_id'] = $row['product_id'];
$row_array['product_names'] = $row['name_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array);
}
mysql_close($conn);
echo json_encode($return_arr);
Unfortunately I also need to get the category_id which is not in the same table, I have tried to modify my query as such, but to no avail:
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' AND `crd_jshopping_products_to_categories` = `product_id` ");
What step am I missing here ? The product_id's match in both tables?
try this query instead and try to understand what I have written in it:
$fetch = mysql_query("
SELECT
p.*,
c.category_id
FROM
crd_jshopping_products as p
INNER JOIN crd_jshopping_products_to_categories as c
ON p.product_id = c.product_id
WHERE
`p.name_en-GB` REGEXP '^$param'
");
This means:
SELECT:
Give me everything from p and the category_id from c.
FROM:
Do this from rows in the tables crd_jshopping_products (referred to as p) and crd_jshopping_products_to_categories (referred to as c), where the rows match on the count of p.product_id is the same as c.product_id.
WHERE:
Only return the rows where p.name_en-GB REGEXP '^$param'.

mysqli query make array out of names

pretty sure this is something easy but i cant figure it out, basicly making a easy query like this:
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
the above query should get all the names out of the database, now i want it to be put into array like this:
$competitors = array(
'Paul A.M. Dirac',
'Hans Christian Oersted',
'Murray Gell-Mann',
'Marie Curie',
'Neils Bohr',
'Richard P. Feynman',
'Max Planck');
how do i get the result from my query into a array like the above on?
$competitors = array();
$result = $mysqli->query("SELECT t.name FROM cups_participants cp
LEFT JOIN teams t on cp.team_id = t.team_id
WHERE cp.cup_id = '1'");
if($result->num_rows > 0)
{
while($rs = $result->fetch_assoc())
{
$competitors[]=$rs['name'];
}
}
echo "<pre />";
print_r($competitors);

how to get all datas in a mysql table with same id

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;
}

PHP: Join two separate mysql queries into the same json data object

I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.

Categories