Foreach and while loop not outputting my fetched data - php

I have the following two prepared statements. The db connection and queries are correct, I have tested them within phpmyadmin. I also tested inside of my while fetch loop to see if I am pulling the data I am supposed to be and I am.
The problem resides in my while and foreach loops or possibly my num rows statement. I am not sure what I am doing incorrectly in there.
I am getting this error:
Warning: mysqli::query() expects parameter 1 to be string, object given
For this while loop:
while ($row2 = $result->fetch_assoc() ) {
I am also getting my else statement..
echo "<p>This topic does not exist.</p>";
Even though the info is echoing out correctly, again I just think my loops are wrong?
Does anyone see what I am doing wrong in my loops?
$con = new mysqli("localhost", "", "", "");
if (mysqli_connect_errno()) {
throw new Exception("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* activate reporting */
$driver = new mysqli_driver();
try {
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
echo $cid . "<br>";
echo $tid;
//Prepare
if ($stmt = $con->prepare("SELECT * FROM forum_topics WHERE `category_id`=? AND `id`=? LIMIT 1")) {
$stmt->bind_param("ii", $cid, $tid);
$stmt->execute();
$stmt->bind_result($topic_id, $category_id, $topic_title, $topic_creator, $topic_last_user, $topic_date, $topic_reply_date, $topic_views);
if (!$stmt) {
throw new Exception($con->error);
}
}
while ($row = $stmt->fetch()) {
$stmt->store_result();
$numrows = $stmt->num_rows;
echo $numrows;
}
if($numrows == 1){
echo "<table width='100%'>";
if ( $_SESSION['user'] ) {
echo "<tr><td colspan='2'><input type='submit' value='Add Reply' onclick=\"window.location =
'forum_post_reply.php?cid=".$cid."$tid=".$tid."'\"> <hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply</p><hr /></td></tr>";
}
}
foreach($stmt as $row) {
//Prepared SELECT stmt to get forum posts
if($stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, `post_date` FROM forum_posts WHERE `category_id`=? AND `topic_id`=?")) {
$stmt2->bind_param("ii", $cid, $tid);
$stmt2->execute();
$stmt2->bind_result($post_id, $post_category_id, $post_topic_id, $post_creator, $post_content, $post_date);
if (!$stmt2) {
throw new Exception($con->error);
}
}
}
if ($result = $con->query($stmt)) {
while ($row2 = $result->fetch_assoc() ) {
echo "<tr><td valign='top' style='border: 1px solid #000000;'>
<div style='min-height: 125px;'>".$row['topic_title']."<br />
by ".$row2['post_creator']." - " .$row2['post_date']. "<hr />" . $row2['post_content'] ."</div></td>
<td width='200' valign='top' align='center' style='border: 1px solid #000000;'>User Info Here!</td></tr>
<tr><td colspan='2'><hr /></td></tr>";
}
} else {
echo "<p>This topic does not exist.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}

if you search on $stmt with ctrl-F in your browser (and ignoring $stmt2), you will notice that $stmt is a prepared statement all the way down to the error line. $stmt comes to life as a return type from prepare, is bound, and executed.
later on you:
if ($result = $con->query($stmt)) {
so $con->query() is expecting a string, not an object, no?
From the manual.
Not that there aren't other things to consider under a microscope, but I hope this narrowly answers the error message for you.
Edit:
Apparently, you cannot use bind_result with select *. Read the gents Accepted Answer to this question. He does 2 examples, 1 with 1 without select *. Also note store_result()
Here is the link to his answer that was upvoted quite a bit.

Related

How to get variable from header in multi query?

i already had forms where I got the variable from the header but the forms have always been pdo and always one single query. This form is connected via mysqli and I just can't figure out how to get a variable.
<?php
$mysqli = new mysqli("localhost:3307", "root", "root", "test");
if($mysqli->connect_errno)
die ("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM contacts WHERE id = ?;";
$query .= "SELECT * FROM companies WHERE id = ?;";
if($mysqli->multi_query($query)) {
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
echo"<table border ='1'>";
echo "<tr>";
foreach($finfo as $f) {
echo "<th>".$f->name."</th>";
}
echo "<br>";
echo "<br>";
echo "</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $v) {
echo "<td>".$v."</td>";
}
echo "</tr>";
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
?>
So the column "id" in both tables is the PK/FK and I want to retrieve information where id = ?.
How do I get the ? variable from the header and pass it on?
I feel like in my past tries I got the variable successfully with this code
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');
[...]
$statement = $mysqli->prepare($query);
$statement->bindParam(1, $id);
$statement->execute();
but didn't echo it correctly.
Thank you in advance!

Error in PHP / MySQL Output

I am trying to fetch my database results but it's not displaying any content.
Please help me to find the error:
<?
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from usermark where sid LIKE '%$search%' LIMIT 0 , 1");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<tr><td colspan='2' bgcolor='#800000'><p align='center'><font face='Verdana' color='#FFFFFF'>RESULTS</font></td></tr>";
echo "<tr><td width='29%'></td><td width='69%'></td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td width='29%'>NAME</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>ID</td><td width='69%'>";
echo $results['sid'];
echo "</td></tr><tr><td width='29%'>ROLL NO.</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>OMR NO.</td><td width='69%'>";
echo $results['somr'];
echo "</td></tr><tr><td width="29%"></td><td width="69%"></td></tr>";
echo "<tr><td width="29%">TOTAL MARKS</td><td width="69%">";
echo $results['smark'];
echo "</td></tr><tr><td width='29%'>MARKS OBTAINED</td><td width='69%'></td></tr>";
echo "<tr><td width='29%'>PERCENTAGE</td><td width='69%'></td></tr>";
echo "</table>";
} else {
echo 'Nothing found';
}
}
?>
You're binding to a variable incorrectly, in your sql string and in bindValue().
Change:
$query = $pdo->prepare("select * from usermark where sid LIKE '%$search%' LIMIT 0 , 1");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
With:
$query = $pdo->prepare("select * from usermark where sid LIKE '%:search%' LIMIT 0 , 1");
$query->bindValue(":search", $search, PDO::PARAM_STR);
You also have a bad conditional statement.
Also Change:
if (!$query->rowCount() == 0) {
To:
if ($query->rowCount() != 0) {

Two many records showing when h_id is identified

I am trying to filter a mysql table using PHP, My aim is when the url is History.php?h_id=1 it only shows the rows that have one in the h_id (H_id is not a unique number)
My code is as below.
<html>
<head>
<title></title>
</head>
<body >
<?php
mysql_connect('localhost', 'root', 'matl0ck') or die(mysql_error());
mysql_select_db("kedb") or die(mysql_error());
$h_id = (int)$_GET['h_id'];
$query = mysql_query("SELECT * FROM Hist WHERE H_ID = '$h_id'") or die(mysql_error());
if(mysql_num_rows($query)=1){
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
?>
<?php
$con=mysqli_connect("localhost","root","matl0ck","kedb");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Hist");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>H_ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['DateMod'] . "</td>";
echo "<td>" . $row['H_ID'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I try to use this it shows all records that has a number in the h_id when I delete a number in this column it shows an error.
My table layout is as below.
Thank you
This is your syntactically incorrect statement
if(mysql_num_rows($query)=1){
A test is done using == and = is a value assignment
if(mysql_num_rows($query) == 1){
//------------------------^^
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
Also
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements and therefore stick to the mysqli_ or PDO database extensions
Your general code seemed to get a bit confused, and you were getting data from a query "SELECT * FROM Hist" that you never seemed to use.
Also the while loop was being terminated before you actually consumed and output the results of the first query.
I also amended the code to use parameterized and prepared queries, and removed the use of the mysql_ which no longer exists in PHP7
<?php
// Use one connection for all script, and make it MYSQLI or PDO
$con=mysqli_connect("localhost","root","matl0ck","kedb");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// if connection fails there is no point doing anything else
exit;
}
//$h_id = (int)$_GET['h_id'];
// prepare and bind values to make the code safe from SQL Injection
// also only select the rows you want
$sql = "SELECT ID, Name, DateMod, H_ID FROM Hist WHERE H_ID = ?";
$stmt = $con->prepare($sql);
if ( ! $stmt ) {
echo $con->error;
exit;
}
$stmt->bind_param("i", $_GET['h_id']);
$stmt->execute();
if ( ! $stmt ) {
echo $con->error;
exit;
}
// bind the query results 4 columns to local variable
$stmt->bind_result($ID, $Name, $DateMod, $H_ID);
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
if($con->affected_rows > 0){
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
while($stmt->fetch()) {
while($row = $stmt->fetch_array()) {
echo "<tr>";
echo "<td>$ID</td>";
echo "<td>$Name</td>";
echo "<td>$DateMod</td>";
echo "<td>$H_ID</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo 'No entry found. Go back';
}
?>

Updating an existing value in php

I'm inserting some values into my database, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result.
$options = '';
$filter=mysql_query("select afnumber from employees WHERE Status='Employed '");
while($row = mysql_fetch_array($filter)) {
$options .="<option >" . $row['afnumber'] . "</option>";
}
$menu="<form id='filter' name='filter' method='post' action=''>
AFNumber : <select name='SelectAF' id='filter' style='color:grey;'>" . $options . "</select>
Added hours: <input type='text' name='AddedHours' style=' padding: 10px;border: solid 2px #c9c9c9; width:50px; height:2px;'>
<input type='submit' name='submit' value='Submit' style='width:80px; height:30px; text-align:center; padding:0px;'>
</form>
<br>
";
/* if(isset($_POST['submit'])){
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
if($addedhours == ""){
$sql="INSERT INTO `editedworkhours` (`AFNumber`,`AddedWH`) VALUES('$selectaf','$addedhours')";
$getResult =mysql_query($sql);
}
else{
$sql2 = "UPDATE editedworkhours SET AddedWH=$addedhours WHERE AFNumber=$selectaf";
$getResult =mysql_query($sql2);
}
}
echo $menu; */
echo '<div class="scrolldiv">';
try {
$conn = new PDO('mysql:host=localhost;dbname=hr', 'root', 'J546');
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$num_rows = $conn->query('SELECT COUNT(*) FROM employees')->fetchColumn();
$pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All'));
echo $pages->display_pages();
echo "<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span>";
$stmt = $conn->prepare("SELECT employees.afnumber,employees.name,employees.dateofemployment,employees.actualpost,employees.department FROM employees WHERE employees.status='Employed' AND (employees.afnumber LIKE '%$search%' OR employees.name LIKE '%$search%') ORDER BY employees.afnumber DESC LIMIT :start,:end");
$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
$ewhtable = "<table class='sortable'><tr><th>AFNumber</th><th>Employee Name</th><th>Years of Service</th><th>Actual Post</th><th>Department</th><th>Added Hours</th></tr>\n";
foreach($result as $row) {
$years=explode("/", $row[2]);
$years[2]=intval(date ('Y')) - $years[2];
$sql="SELECT addedwh FROM editedworkhours WHERE afnumber='$row[0]'";
$var = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result2 = $stmt->fetchAll();
foreach ($result2 AS $row2) {
$var .= $row2['addedwh'] . "\n";
}
$ewhtable .= "<tr><td>$row[0]</td><td>$row[1]</td><td>$years[2]</td><td>$row[3]</td><td>$row[4]</td><td>$var</td></tr>\n";
}
$ewhtable .= "</table>\n";
echo $ewhtable;
exportTable(str_replace("&","",$ewhtable),"EmployeeWorkingHoursTable");
echo $pages->display_pages();
echo "<p class=\"paginate\">Page: $pages->current_page of $pages->num_pages</p>\n";
echo "</div>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
If AddedHours input value has only a space, your comparison if($addedhours == "") will fail.
Always trim the values before comparison.
$addedhours = trim($_POST['AddedHours']);

Database output not showing. Getting else statement

I have the following code that I am not getting any of my db output to appear on my site. I only get the else statement echo response of echo "<p>This topic does not exist.</p>";, but I have topics in my database.
Does anyone see anything in my code that would cause this to not display any output and make the else statement appear? If there isn't, how can I debug this to figure out the issue? I am not getting any errors from my prepared statements, so it has to be within the numrows statement or while loop.
$con = mysqli_connect("localhost", "root", "", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
//Prepared SELECT stmt to get forum topics
$stmt = $con->prepare("SELECT * FROM forum_topics WHERE `category_id`=? AND id=? LIMIT 1");
if ( !$stmt || $con->error ) {
die('Select topics prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('ii', $cid, $tid)) {
die('Select topics bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('Select topics execute() failed: ' . htmlspecialchars($stmt->error));
}
$numrows = $stmt->num_rows;
if($numrows == 1){
echo "<table width='100%'>";
if ( $_SESSION['user'] ) {
echo "<tr><td colspan='2'><input type='submit' value='Add Reply' onClick=\"window.location =
'forum_post_reply.php?cid=".$cid."$tid=".$tid."'\"> <hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply</p><hr /></td></tr>";
}
while($row = mysqli_fetch_assoc($stmt)){
//Prepared SELECT stmt to get forum topics
$stmt2 = $con->prepare("SELECT * FROM forum_posts WHERE `category_id`=? AND topic_id=?");
if ( !$stmt2 || $con->error ) {
die('Select topics prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('ii', $cid, $tid)) {
die('Select topics bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Select topics execute() failed: ' . htmlspecialchars($stmt2->error));
}
while($row2 = mysqli_fetch_assoc($stmt2)){
echo "<tr><td valign='top' style='border: 1px solid #000000;'>
<div style='min-height: 125px;'>".$row['topic_title']."<br />
by ".$row2['post_creator']." - " .$row2['post_date']. "<hr />" . $row2['post_content'] ."</div></td>
<td width='200' valign='top' align='center' style='border: 1px solid #000000;'>User Info Here!</td></tr>
<tr><td colspan='2'><hr /></td></tr>";
}
}
} else {
echo "<p>This topic does not exist.</p>";
}
$cid = $_GET['cid']; is the category id
`$tid = $_GET['tid'];` is another id
To quote the documentation:
Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
The following should do the trick:
$stmt->store_result();
$numrows = $stmt->num_rows;
if ($numrows == 1) {
// etc...

Categories