Convert mysqli to pdo prepared statement - php

I cant get my pdo prepared statement code to pull the records! Only if I write it in MySQLi code.
filter_month.php with both codes below.
filter_month.php--------PDO-Conversion---Prevent SQL Injection Not working!
<?php
{
include 'db_connection2.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
year(date) = ? AND month(date) = ?
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["year"]],[$_POST["month"]]);
$stmt->fetchAll(PDO::FETCH_ASSOC);
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".001%"><font size=2><span>Attended</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>'; }
$pdo=null;
// By this way you can close connection in PDO.
?>
filter_month.php -----mysqli-----This code works!
<?php
{
include 'db_connection.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
YEAR(date) = '".$_POST["year"]."'
AND
Month(date) = '".$_POST["month"]."'
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$result = mysqli_query($conn, $query);
$conn->close();
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".02%"><font size=2><span>Attended</span></th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
I have tried many different ways to write the code but, cant get to pull records. Just now learning about pdo.
Also trying to add an image of the client side reportmonthpage.php but cant figure out how to post image.
Here is just my filter_year.php, not year and month, and it works. If I remove the brackets as you have suggested it wont pull records any longer.
<?php
{
include 'db_connection2.php';
$query = "SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
YEAR(date) = ?
AND
ar.present = 1
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["year"]]);
$result = $query;
$output .= '
<table class="table table-bordered">
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Total Year Attendance</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>';
}
$pdo=null;
// By this way you can close connection in PDO.
?>

You want an array in the execute function and you've misplace brackets in such a way that you do not have an array.
[$_POST["year"]],[$_POST["month"]] should be [$_POST["year"],$_POST["month"]] to create the array. You have too many brackets.

Here is what I came up with that works! I'm sure it must be wrong, but it works!
<?php
{
include 'db_connection2.php';
$query = " SELECT
g.name as `group`,
COUNT(ar.present) as attended
FROM
attendance_record ar
INNER JOIN
_person p
ON ar.personid = p.id
INNER JOIN
_person_group g
ON ar.groupid = g.id
-- WHERE
AND
month(date) = ? AND year(date) = ?
AND
ar.present = 1
GROUP BY g.name
ORDER BY ar.date, g.name ASC
";
$stmt = $pdo->prepare($query);
$stmt->execute([$_POST["month"],$_POST["year"]] );
$result = $query;
//-----------------------------Table------------------------------------//
$output .= '
<table class="table table-bordered">
<div align="center"><font size=4>
Total present (by Class)-------PDO------ Not Working Code</font>
</div>
<tr>
<th style="text-align:center;" width=".001%"><font size=2><span>Class</span></th>
<th style="text-align:center;" width=".001%"><font size=2><span>Attended</span></th>
</tr>
';
foreach($stmt as $row)
{
$output .= '
<tr>
<td style="text-align:center;">' . $row['group'] . '</td>
<td style="text-align:center;">' . $row['attended'] . '</td>
</tr>
';
}
$output .= '</table>'; }
$pdo=null;
// By this way you can close connection in PDO.
?>
Thank you all for your time!

Related

Get a while loop to run "X" number of times with two conditions in PHP

So i have this code:
<?php
require_once('../../ccconnect.php');
$query = "SELECT * FROM orgs";
$response = #mysqli_query($dbc, $query);
if($response){
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr>
<td align="left"> <b>Logga</b> </td>
<td align="left"> <b>Namn</b> </td>
<td align="left"> <b>Andel till ändamål</b> </td>
<td align="left"> <b>Vinst</b> </td> </tr>';
while($row = mysqli_fetch_array($response))){
echo '<tr>
<td align="left">' . $row['logo'] . '</td>
<td align ="left">' . $row['name'] . '</td>
<td align ="left">' . $row['chare'] . '</td>
<td align ="left">' . $row['profit'] . '</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "Kunde inte genomföra databaskomandot<br>";
echo mysqli_error($dbc);
}
?>
The code will print out a table of results from my database, but i want to limit the results i get to only show 5 results for example. How would i do this?
Use the LIMIT clause in SQL.
SELECT * FROM my_table
LIMIT 5;
https://dev.mysql.com/doc/refman/5.5/en/select.html
http://www.w3schools.com/php/php_mysql_select_limit.asp
You need to limit the query or limit the loop. (I like the first option better).
You have this query:
$query = "SELECT * FROM orgs";
Wanna get 5 results only?
$query = "SELECT * FROM orgs LIMIT 5";

Only display once in while loop

Im using a while loop to go through a DB and pull out some questions and answers. That mostly works apart from the facts the the question order isnt correct.
My question is how do I get the questions to print correctly
Eg :
Q1
Q2
A to Q1
Q3
A to Q2
Blank
A to Q3
Heres an image of what I mean:
Here is the code im using minus the query because I know it works. I think its the if statement thats wrong.
$result = mysqli_query($conn, "SELECT
q.QText, q.id AS QId, ua.id, a.AText, ca.id, ca.Answer_ID,
case when a.id = ua.Answer_ID then 'x' else NULL end as IsUserAnswer ,
case when a.id = ca.Answer_ID then 'x' else NULL end as IsCorrectAnswer
FROM user_answers ua
INNER JOIN question q ON q.id = ua.Question_ID
INNER JOIN answer a ON a.Question_ID = q.id
INNER JOIN correct_answer ca ON ca.Question_ID = q.id
WHERE ua.Test_ID=1
ORDER BY q.ID") or die(mysqli_error($conn));
$lastQuestionID = 0;
while ($data2 = mysqli_fetch_array($result))
{
if ($data2['QId'] != $lastQuestionID)
echo '<p>Q. ' . $data2['QText'] . '</p>
<table class="striped centered">
<thead>
<tr>
<th>Answer</th>
<th>Your Answer</th>
<th>Correct Answer</th>
</tr>
</thead>';
$lastQuestionID = $data2['QId'];
echo '
<tr>
<td>' . $data2['AText'] . '</td>
<td>' . $data2['IsUserAnswer'] . '</td>
<td>' . $data2['IsCorrectAnswer'] . '</td>
</tr>';
}
echo "</table>";
Your table closing is defined incorrectly. Do this instead:
$result = mysqli_query($conn, "Query") or die(mysqli_error($conn));
$lastQuestionID = 0;
$isTableOpen = false;
while ($data2 = mysqli_fetch_array($result)) {
if ($data2['QId'] != $lastQuestionID) {
if ($isTableOpen) {
echo '</table>';
}
$isTableOpen = true;
echo '<p>Q. ' . $data2['QText'] . '</p>
<table class="striped centered">
<thead>
<tr>
<th>Answer</th>
<th>Your Answer</th>
<th>Correct Answer</th>
</tr>
</thead>';
}
echo '
<tr>
<td>' . $data2['AText'] . '</td>
<td>' . $data2['IsUserAnswer'] . '</td>
<td>' . $data2['IsCorrectAnswer'] . '</td>
</tr>';
$lastQuestionID = $data2['QId'];
}
if ($isTableOpen) { // Close last open table
echo '</table>';
}

php foreach outside the function

i'm learning php.
i have a function with mysql query select.
than i use it with foreach list..
but it work me only if the foreach is inside the function.
i don't know how to get it work outside the function..
what i'm doing wrong?
working code - https://phpbox.info/d3GCP
no working code:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>
thanks a lot
You function volaco() need return type
return $apps= $db->loadObjectList();
Read Returning values
Add a return to your volaco() function, $apps is out of the scope.
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
return $db->loadObjectList();
?>
Try this:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
return $apps;
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>

Display data from join?

I have a page where it displays a movie review, that is displayed by a link Read Review on this same page I would also like to display the movie title. So do I have to use a join to display the information or is there a simpler way of doing it ? I have tried using a few queries but I end up getting all the film titles for the one review.
This is where the query first starts on the film.php
$query = "SELECT films.movie_title, films.rating, films.actor, reviewed.review,
users.username
FROM films
LEFT JOIN reviewed ON films.movie_id=reviewed.movie_id
LEFT JOIN users ON films.user_id=users.user_id";
$result = mysql_query($query) or die ("Could not execute mysql" . mysql_error());
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran ok, display records.
echo "<p> There are curently $num records.</p>";
// Table header.
echo '<table border="1" align="center" cellspacing="0" cellpadding="5">
<tr>
<td align="left"><b>Movie Title</b></td>
<td align="left"><b>Leading Actor</b></td>
<td align="left"><b>Rating</b></td>
<td align="left"><b>Author</b></td>
<td align="left"><b>Review</b></td>
</tr>';
// Fetch and print all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>
<td align="left">' . $row['movie_title'] . '</td>
<td align="left">' . $row['actor'] . '</td>
<td align="left">' . $row['rating'] . '</td>
<td align="left">' . $row['username'] . '</td>
<td align="left"> Read Review
</tr> ';
}
}
?>
Now on this page is displays the review but I would like to display the movie_title within the sub_review container.
<body>
<div id="sub_review_container">
<?php
?>
</div>
<div id="Review_container">
<?php
$review = $_GET['id'];
echo $review;
?>
</div>
</body>
You are missing the id of the review in the query of which you want to show the review.
Also because of left join. It is showing all records. You should use inner join for reviews and films. It should be like:
$query = "SELECT films.movie_title as movie_title, films.rating, films.actor, reviewed.review, users.username FROM films INNER JOIN reviewed ON films.movie_id=reviewed.movie_id INNER JOIN users ON films.user_id=users.user_id where reviewed.id = ... "
...reviewed.id will be the Id you pass from page.

grouping class names together in my CMS php

I am done with a CMS school system which i created from scratch for practice in php. My question is for example I have Accounting 101, Computer Science 101, however there must multiple times for Accounting 101. For example: Ticket 1035, 1036 are both Accounting 101 and they should appear in the same table, but in my code it shows them in different classes. Here is my code.
if(isset($_GET['id']))
{
$category = $_GET['id'];
$sql = "SELECT * FROM classes WHERE category_id = " . $category;
$query2 = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($query2))
{
?>
<center><h3><?php echo $row->class_name . '-' . $row->units; ?> </h3></center>
<table border ="0" wdith="100%">
<tr>
<td>
<strong>Description: </strong>
<?php echo $row->class_description; ?>
</tr>
</td>
</table>
<br/>
<table border="1" width="44%">
<tr>
<td width="60"><b>Ticket</b> </td>
<td width="123"><b>Days</b></td>
<td width="120"><b>Hours</b></td>
<td width="64"><b>Room</b></td>
<td><b>Instructor</b></td>
</tr>
<tr>
<td width="60"> <?php echo $row->ticket; ?> </td>
<td width="123"><?php echo $row->days; ?></td>
<td width="120"><?php echo $row->start_hours . $row->time_format . '-' . $row->end_hours . $row->time_format2 ; ?> </td>
<td width="64"> <?php echo $row->room_number; ?></td>
<td><?php echo $row->instructor_name; ?></td>
</tr>
}//end while
}//end if
Its showing Accounting 101 with different tickets in different tables, but it should be all in 1 table. Thanks.
You need a double loop if you're trying to get records inside of records. For example:
while ($row1 = mysql_fetch_object($query1))
{
echo $row1->ParentName;
$query2 = 'select * from `mytable` where `myForeignKey` = ' . $row1->ParentId;
while ($row2 = mysql_fetch_object($query2))
{
echo $row2->ChildName;
}
}
You could also do a left join. Let me know if you need a sample of that.
Edit:
The left join would be done like this:
$sql = "select * from `classes` as a where category_id = '{$category}' left join `tickets` as b on a.id = b.class_id"
Ref. http://www.w3schools.com/sql/sql_join_left.asp

Categories