htmlentities function breaking a while loop - php

I have a piece of code which is driving me crazy please help!
Basically I have result set from a database returning 3 rows of data, the data in the field I'm interested in is as below:
row 1 - "the Retention Release Date;"
row 2 - "where applicable, any later due date for Retention release under clause 4·15·2·3; or"
row 3 - "the date of issue of the Contractor's statement under clause 4·6·2 or, in default, the last date for issue of that statement."
The array is $result_set and the associative key is ['subsubclausedesc'] so the code I am running is:
while($result_set = $database->fetch_array($result))
{
echo htmlentities($result_set['subsubclausedesc']);
}
The problem I am having is that only the 1st row is being returned to the screen, if I echo without htmlentities I get all 3 rows, what am I doing wrong?

You can try this with stripslashes
while($result_set = $database->fetch_array($result))
{
echo htmlentities(stripslashes($result_set['subsubclausedesc']));
}

Related

Retrieve array from postgres

Very basic question but couldn´t find a solution.
In a table with some values I try to store in 1 column a array (int[]) and retrieve it. The storing and searching works fine but if I select it I get it as string in php.
Table week
col id (int) = 1
col days (int[]) = {1,1,1,1,1,0,0}
PHP
$query = SELECT id, days, manyother FROM week //array_to_json(days) does the same result
$pdo->setAttribute( PDO::ATTR_CASE, PDO::CASE_NATURAL );
$result = $pdo->query($query);
$test = $result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($test)
Returns:
id: 1
days: "[1,1,1,1,1,0,0]"
manyother: ""
I´m sure I miss just something with json_encode/decode
Edit: its not affected by json_encode, I debuged it and before it returns the value like '[1,1,1,1,1,0,0]'.
Edit 2: Found a solution which works but increases the loading time 15* times :D So the question is still open but I have a workaround for the moment.
foreach($test as $key => $value){
$test[$key]['days'] = json_decode($value['days']);
}
when selecting array, you can hack the way array is displayed:
t=# select json_build_array(array[1,2,3,4])->0;
?column?
-----------
[1,2,3,4]
(1 row)
It should be easily evaluated by php then with eval. Or even json_agg on whole data set and then eval:
t=# select json_agg(s162) from s162;
json_agg
[{"i":0,"a":[1,2,3,4]},
{"i":1,"a":[1,4]}]
(1 row)
Time: 0.281 ms

PHP: Running if and else if inside a while loop?

I'm trying to run if and else if inside a while loop in my PHP code.
The code looks like this:
<?php
$sql = "SELECT * FROM table ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$deviceType = $row["deviceType"];
if($deviceType == 'iPhone' || $deviceType == 'iPad'){
echo 'IOS';
}else if($deviceType == 'Android'){
echo 'Android';
}
}
} else {
}
?>
The code above works (sort of) but not as I was expecting it.
To give you an example, lets say I have 2 rows in MYSQL database.
like this:
id deviceType
1 Android
2 iPhone
when i run my PHP code above, I get this echo-ed on my page:
IOS
IOS
Android
Android
BUT I only have 2 rows in the database so the result should be:
IOS
Android
Could someone please advise on this issue?
This question is clearly misrepresenting your actual code/data.
When your database table has 2 rows, but you are receiving 4 rows then the onus is not on the fetching function, but on your query or database table data.
If your actual query is as posted in your question, then your table data contains more than two rows.
If your actual query is different from what you posted (say, joining the table with a copy of itself), then your data is fine and your query is failing you.
Regardless of if you are using mysqli_fetch_array($result), mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result), your while() loop will only do one iteration for each row of data.
The difference in resultset fetching functions:
mysqli_fetch_array($result):
array(0=>'1', 'id'=>'1', 1=>'Android', 'deviceType'=>'Android') // 1 row w/ 4 elements
array(0=>'2', 'id'=>'2', 1=>'iPhone', 'deviceType'=>'iPhone') // 1 row w/ 4 elements
mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result):
array('id'=>'1', 'deviceType'=>'Android') // 1 row w/ 2 elements
array('id'=>'2', 'deviceType'=>'iPhone') // 1 row w/ 2 elements
I will rewrite your code and implement some good practices:
if($result=mysqli_query($db_conx,"SELECT `deviceType` FROM `table` ORDER BY `id`;")){
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
echo ($row["deviceType"]=="Android"?"Android":"IOS"); // inline condition is a personal preference
}
}else{
echo "No rows in `table`.";
}
}
Only bother declaring a variable if you will use its value more than once (*or if it dramatically improves readability to separate it from its single use.)
So that your variable names are intuitive, name your query variable $sql or $query; and name your query's result variable $result.
Only SELECT columns that you intend to use; * is unnecessary for your case.
Backtick ` wrapping is not required on column and table names, but doing so will avoid any potential clashes with MySQL keywords.
Perform a conditional check and declare the $result variable as false or [resultset] in a single step.
Always check that $result is true before calling any functions that access the resultset. (e.g. mysqli_num_rows() and mysqli_fetch_assoc()).
if(mysqli_num_rows($result)){ will check for a non-falsey value -- I mean 0 equates to false and anything greater than 0 will be true.
Your code appears to be perfectly fine. However, instead of the expected output, you get more items than needed. If I am not mistaken, this means that you have duplicate deviceType in your database table. $productCount probably has a value of 4. You can get two values if you use this query instead:
SELECT DISTINCT `deviceType` FROM `table` ORDER BY `id`
but while this should fix the output you get, your data will still hold duplicates, so you might want to look into the data of your table and into the way it was created, find out and fix the problem.
the answer is very simple you are fetching the results twice with the while loop change this line
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
to
while($row = mysqli_fetch_assoc($query)){
then it will work right, you can see buy the order iPhone iPhone android android that is doing it twice instead of once per loop

Getting answers from a database

I am making an online test script where you can input the answers in the input elements. Once the test is submitted I want the database's answers to be compared with the inputted answers to say whether it is wrong or not, however the script I am using is not working! :S
Here is the problem!
In the database, I have 4 out of 50 ready answers set (not all yet) when I answer both 4 correct or wrong it returns them being incorrect. It lists all the answers, whether they're correct or incorrect in the page but it's not working correctly, no matter what inputs I do, it all the answers up to 49 say incorrect, then for some reason 50 says correct?...
Here is my script:
<?php
$con=mysqli_connect("localhost","dstsbsse","pass","user");
if (mysqli_connect_errno($con))
{
echo "ERROR - Failed to connect to MySQL Server. Please contact an Administrator at English In York: " . mysqli_connect_error();
}
//Set variables to hold output data and total score.
$output="";
$score=0;
//for-next loop. This means "Set n to value one. Every time through the loop (between {}) increase n by one. Do this while n is less than or equal to 50"
for($n=1;$n<=50;$n++)
{
$sql="SELECT a$n FROM answer WHERE 1";
// $sql="SELECT * FROM answer WHERE name='a$n'"; //sql is specific to your table of course - you will need to change this.
$result = $con->query($sql); // perform the query
$row = $result->fetch_assoc(); //load the result into the array $row
$key="a".$n; //concatenate to generate the $_POST keys
if($row['answer']==$_POST[$key]) //compare the data from the table with the answer
{
//answer is correct
$score++;
$output.="Answer $n is correct</BR>"; //add responses to the output string
}
else
{
$output.="Answer $n is incorrect</BR>";
}
}
$output.="Total score: $score/50"; //add the score
echo $output; //echo to screen.
Here is an example of one of the questions answer boxes:
<input type="text" name="a1" id="a1" required>
How can I fix this?
Fetching a query like:
SELECT a1 FROM answer
would return $row['a1'], instead of $row['answer']
So you should be using the column name, not the table one

fetch on PDO returns only one row and first character. why?

i'm new on PDO with PHP and i want your help. i made a function with a select statement and if the query has value greater than 0 it returns the fetch.
$this->result->setFetchMode(PDO::FETCH_OBJ);
if ($this->result->rowCount() > 0) {
return $this->result->fetch();
}
and on my main program i have this
foreach ($category_results as $row){
echo .$row['id_category'].' '. $row['name'];
}
this command echo only 1 and F twice but if i put only $row it echo all the results correct e.g 1 Food, 2 Drinks. how i can echo the results separately like the example i have above? i want to put them in a list box
thank you
You are using:
$this->result->setFetchMode(PDO::FETCH_OBJ);
So you will have your rows stored in objects, also see the manual.
To get them, you can use:
echo .$row->id_category.' '. $row->name;
Also note that fetch only gets one row, to get all rows, use fetchAll. However, without seeing the complete code, I'm not sure whether you would need that.

PHP: mysql_fetch_array() in a while-loop takes too long

I am creating an online calendar for a client using PHP/MySQL.
I initiated a <table> and <tr>, and after that have a while loop that creates a new <td> for each day, up to the max number of days in the month.
The line after the <td>, PHP searches a MySQL database for any events that occur on that day by comparing the value of $i (the counter) to the value of the formatted Unix timestamp within that row of the database. In order to increment the internal row counter ONLY when a match is made, I have made another while loop that fetches a new array for the result. It is significantly slowing down loading time.
Here's the code, shortened so you don't have to read the unnecessary stuff:
$qry = "SELECT * FROM events WHERE author=\"$author\"";
$result = mysql_query($qry) or die(mysql_error());
$row = mysql_fetch_array($result);
for ($i = 1; $i <= $max_days; $i++) {
echo "<td class=\"day\">";
$rowunixdate_number = date("j", $row['unixdate']);
if ($rowunixdate_number == $i) {
while ($rowunixdate_number == $i) {
$rowtitle = $row['title'];
echo $rowtitle;
$row = mysql_fetch_array($result);
$rowunixdate_number = date("j", $row['unixdate']);
}
}
echo "</td>";
if (newWeek($day_count)) {
echo "</tr><tr>";
}
$day_count++;
}
The slowness is most likely because you're doing 31 queries, instead of 1 query before you build the HTML table, as Nael El Shawwa pointed out -- if you're trying to get all the upcoming events for a given author for the month, you should select that in a single SQL query, and then iterate over the result set to actually generate the table. E.g.
$sql = "SELECT * FROM events WHERE author = '$author' ORDER BY xdate ASC";
$rsEvents = mysql_query($sql);
echo("<table><tr>");
while ($Event = mysql_fetch_array($rsEvents)) {
echo("<td>[event info in $Event goes here]</td>");
}
echo("</tr></table>");
Furthermore, it's usually a bad idea to intermix SQL queries and HTML generation. Your external data should be gathered in one place, the output data generated in another. My example cuts it close, by having the SQL immediately before the HTML generation, but that's still better than having an HTML block contain SQL queries right in the middle of it.
Have you run that query in a MySQL tool to see how long it takes?
Do you have an index on the author column?
There's nothing wrong with your PHP. I suspect the query is the problem and no index is the cause.
aside from their comments above, also try to optimize your sql query since this is one of the most common source of performance issues.
let say you have a news article table with Title, Date, Blurb, Content fields and you only need to fetch the title and display them as a list on the html page,
to do a "SELECT * FROM TABLE"
means that you are requiring the db server to fetch all the field data when doing the loop (including the Blurb and Content which you are not going to use).
if you optimize that to something like:
"SELECT Title, Date FROM TABLE" would fetch only the necessary data and would be more efficient in terms of server utilization.
i hope this helps you.
Is 'author' an id? or a string? Either way an index would help you.
The query is not slow, its the for loop thats causing the problem. Its not complete; missing the $i loop condition and increment. Or is this a typo?
Why don't you just order the query by the date?
SELECT * FROM events WHERE author=? ORDER BY unixdate ASC
and have a variable to store the current date you are on to have any logic required to group events by date in your table ex. giving all event rows with the same date the same color.
Assuming the date is a unix timestamp that does not account for the event's time then you can do this:
$currentDate = 0;
while(mysql_fetch_array($result)){
if($currentDate == $row['unixdate']){
//code to present an event that is on the same day as the previous event
}else{
//code to present an even on a date that is past the previous event
//you are sorting events by date in the query
}
//update currentDate for next iteration
$currentDate = $row['unixdate'];
}
if unixdate includes the event time, then you need to add some logic to just extract the unix date timestmap excluding the hours and minutes.
Hope that helps

Categories