Cannot fetch row id using pdo [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I cant fetch my db row using PDO. Currently I am using fetch(PDO::FETCH_ASSOC) but my result is showing blank.
This is my code:
<?php
ini_set('display_errors', 1);
//create_cat.php
include 'dbfunctions.php';
include 'forum_header.php';
$db = getConnection();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_GET['id'];
$sql = "SELECT
topicid,
topicsubject
FROM
topics
WHERE
topics.topicid = :id ";
$result = $db->prepare($sql);
$result->bindParam(":id", $id, PDO::PARAM_INT);
$result->execute();
$numrows = $result->fetchColumn();
if(!$result)
{
echo 'The topic could not be displayed, please try again later.';
}
else
{
while($topicrow = $result->fetchAll(PDO::FETCH_ASSOC))
{
echo "hello";
//display post data
echo '<table class="topic" border="1">';
echo '<tr>';
echo '<th colspan="2">' . $topicrow['topicsubject'] . '</th>';
echo '</tr>';
//fetch the posts from the database
$posts_sql = "SELECT
posts.topicid,
posts.postcontent,
posts.postdate,
posts.postby,
users.userID
FROM
posts
LEFT JOIN
users
ON
posts.postby = users.userID
WHERE
posts.topicid = :id ";
$posts_result = $db->prepare($posts_sql);
$posts_result->bindParam(":id", $id, PDO::PARAM_INT);
$posts_result->execute();
$posts_numrows = $posts_result->fetchColumn();
if(!$posts_result)
{
echo '<tr><td>The posts could not be displayed, please try again later.</tr></td></table>';
}
else
{
while($posts_row = $posts_result->fetch(PDO::FETCH_ASSOC))
{
echo '<tr class="topic-post">
<td class="user-post">' . $posts_row['userID'] . '<br/>' . date('d-m-Y H:i', strtotime($posts_row['postdate'])) . '</td>
<td class="post-content">' . htmlentities(stripslashes($posts_row['postcontent'])) . '</td>
</tr>';
}
}
if(!$_SESSION['CurrentUser'])
{
echo '<tr><td colspan=2>You must be signed in to reply. You can also sign up for an account.';
}
else
{
//show reply box
echo '<tr><td colspan="2"><h2>Reply:</h2><br />
<form method="post" action="forum_reply.php?id=' . $row['topicid'] . '">
<textarea name="reply-content"></textarea><br /><br />
<input type="submit" value="Submit reply" />
</form></td></tr>';
}
//finish the table
echo '</table>';
}
}
include 'forum_footer.php';
?>
After the while loop I cannot fetch my row['topicsubject'] did I missed something .Can anyone help me with this. Thank you.

Wow so much debate for a small problem. Your first call to fetchColumn() fetches the data from the only row there is. So there is nothing left for fetchAll() to fetch.

Related

SQL Selection not outputting data

Starting off, I'm kind of stumbling in the dark here with PHP/SQL, and don't really know how to bugtest that well, so forgive my vagueness about the exact nature of the problem. Moving on.
I have some code which grabs category ids, names, and descriptions from an SQL table, and saves the result to a variable. This is done through statement preparing to avoid an possibility of SQL injection. This value is then fed into some PHP which checks if the query had any response, and if so prints that into a table.
<?php
//create_cat.php
include_once (__DIR__ . '/../includes/db_connect.php');
include_once (__DIR__ . '/../includes/functions.php');
include_once (__DIR__ . '/header.php');
ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1);
$stmt = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
if (login_check($mysqli) == true) {
if(!$result = $mysqli->query($stmt)){
echo 'The categories could not be displayed, please try again later.';
} else {
if ($result->num_rows === 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'];
echo '</td>';
echo '<td class="rightpart">';
echo 'Topic subject at 10-10';
echo '</td>';
echo '</tr>';
}
}
}
} else {
echo <<<error
<p>
<span class="error">You are not authorized to access this page.</span> Please login.
</p>
error;
}
include_once (__DIR__ . '/footer.php');
?>
However, the table SQL table definitely has values, but the PHP is only outputting: "The categories could not be displayed, please try again later."
Ok, got it working. I removed $stmt_prep commands, made sure to only use mysqli commands, and fixed some syntax errors. Code still has broken HTML, but the problem I was asking about is fixed.
If you wanted to keep the object oriented style, the main mistake was closing the statement before fetching the results. PHP will free up the statement at the end of the script anyway, but once you've called $stmt->close(); you won't be able to read any data from the query. Since PHP does copy by reference, $result = $stmt; doesn't copy the data, it just references the same closed statement.
The fetch syntax also isn't quite what you had: you need to bind some placeholder variables with eg $stmt->bind_result($name, $description); and then call $stmt->fetch() instead of fetch_assoc.
I'm not clear exactly what login_check does but it would seem to me that you'd want to put this check earlier so that the query is not executed if the user is unauthorized.
Your original code would end up looking something like:
<?php
if (login_check($mysqli) == true) {
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
$stmt->bind_result($name, $description);
while ($stmt->fetch()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $name . '</h3>'
. $description;
echo '</td>';
echo '<td class="rightpart">';
echo 'Topic subject at 10-10';
echo '</td>';
echo '</tr>';
}
}
} else {
echo 'The categories could not be displayed, please try again later.';
}
} else {
echo <<<error
<p>
<span class="error">You are not authorized to access this page.</span> Please
login.
</p>
error;
}

Get id from url using PDO [duplicate]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I cant fetch my db row using PDO. Currently I am using fetch(PDO::FETCH_ASSOC) but my result is showing blank.
This is my code:
<?php
ini_set('display_errors', 1);
//create_cat.php
include 'dbfunctions.php';
include 'forum_header.php';
$db = getConnection();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_GET['id'];
$sql = "SELECT
topicid,
topicsubject
FROM
topics
WHERE
topics.topicid = :id ";
$result = $db->prepare($sql);
$result->bindParam(":id", $id, PDO::PARAM_INT);
$result->execute();
$numrows = $result->fetchColumn();
if(!$result)
{
echo 'The topic could not be displayed, please try again later.';
}
else
{
while($topicrow = $result->fetchAll(PDO::FETCH_ASSOC))
{
echo "hello";
//display post data
echo '<table class="topic" border="1">';
echo '<tr>';
echo '<th colspan="2">' . $topicrow['topicsubject'] . '</th>';
echo '</tr>';
//fetch the posts from the database
$posts_sql = "SELECT
posts.topicid,
posts.postcontent,
posts.postdate,
posts.postby,
users.userID
FROM
posts
LEFT JOIN
users
ON
posts.postby = users.userID
WHERE
posts.topicid = :id ";
$posts_result = $db->prepare($posts_sql);
$posts_result->bindParam(":id", $id, PDO::PARAM_INT);
$posts_result->execute();
$posts_numrows = $posts_result->fetchColumn();
if(!$posts_result)
{
echo '<tr><td>The posts could not be displayed, please try again later.</tr></td></table>';
}
else
{
while($posts_row = $posts_result->fetch(PDO::FETCH_ASSOC))
{
echo '<tr class="topic-post">
<td class="user-post">' . $posts_row['userID'] . '<br/>' . date('d-m-Y H:i', strtotime($posts_row['postdate'])) . '</td>
<td class="post-content">' . htmlentities(stripslashes($posts_row['postcontent'])) . '</td>
</tr>';
}
}
if(!$_SESSION['CurrentUser'])
{
echo '<tr><td colspan=2>You must be signed in to reply. You can also sign up for an account.';
}
else
{
//show reply box
echo '<tr><td colspan="2"><h2>Reply:</h2><br />
<form method="post" action="forum_reply.php?id=' . $row['topicid'] . '">
<textarea name="reply-content"></textarea><br /><br />
<input type="submit" value="Submit reply" />
</form></td></tr>';
}
//finish the table
echo '</table>';
}
}
include 'forum_footer.php';
?>
After the while loop I cannot fetch my row['topicsubject'] did I missed something .Can anyone help me with this. Thank you.
Wow so much debate for a small problem. Your first call to fetchColumn() fetches the data from the only row there is. So there is nothing left for fetchAll() to fetch.

How can I stay on the same page, when I delete a record?

I'm developing a comments system. Right now it is very simple. But I am a bit stuck.
I have a set off rooms that you can book. And for each of the rooms, you can submit comments to them.
When I click my to acess the comments of a room, I sent the room id with the URL, as you can see by the following code:
if (isset ( $_GET ['id'] )) {
$room_id = $_GET ['id'];
}
$user_id = $_SESSION ['id'];
if ($_POST){
extract($_POST);
$register = $comment->createComment($room_id, $user_id, $comments);
}
?>
<div id="comments">
<?php echo $comment->getComments($room_id); ?>
</div>
<div id="comment-form">
<h3>New Comment</h3>
<form action="" method="post">
<table>
<tr>
<td><textarea name="comments" cols="40" rows="8"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Submit Comment" /></td>
</tr>
</table>
</form>
</div>
To get my comments I call my function getComments($room_id)
public function getComments($room_id) {
$str = "SELECT * FROM comments WHERE room_id = $room_id";
$result = $this->db->mysqli->query ($str);
if ($result->num_rows > 0) {
$string = "<table><thead><tr><th>#ID</th><th>Room id</th><th>user id</th><th>comments</th><th>Timestamp</th></tr></thead><tbody>";
while ( $row = $result->fetch_assoc () ) {
$string .= "<tr><td>" . $row ['id'] .
"</td><td>" . $row ['room_id'] .
"</td><td>" . $row ['user_id'] .
"</td><td>" . $row ['comments'] .
"</td><td>" . $row ['timestamp'] .
"</td><td>[<a href='deleteComment.php?id=" . $row ['id'] . "'>Delete</a>]</td> ";
}
$string .= "</tbody></table>";
return $string;
}
}
As you can see I create a link that goes to deleteComment.php and sent the link of the comment that I want to delete with it.
On that page I call a new function:
if ($comment->deleteComment($_GET['id']))
{
echo "comment deleted"
}
else
{
echo "Something went wrong.s";
}
And finally, my delete comment function:
public function deleteComment($id)
{
$sql = "DELETE FROM comments WHERE id = ?";
if (!$result = $this->db->mysqli->prepare($sql))
{
return false;
}
if (!$result->bind_param('i', $id))
{
return false;
}
return $result->execute();
}
All of this is working. But my question is: How can I delete the comments and still stay on the original page that displays the comments, and not go to the deleteComments.php page? I'm not looking for an AJAX solution. It would be nice if I could just stick to PHP.
As Rakesh suggested, you can use the header() function in your deleteComment function or you can just link to the same page but with comment id to be deleted
instead of:
href='deleteComment.php?id=" . $row ['id'] . "'>
do:
href='?id=" . $row ['delete_comment_id'] . "'>
and delete the comment before creating the list of comments
Just link the delete "button" to the normal comments page with a seperate delete GET or POST value (instead of id), then at the beginning of your comments page if it is set.
Eg: yourpage.com/comments.php?delete=14
if (isset($_GET['delete']))
{
$comment->deleteComment($_GET['delete']);
}
BUT(!) really be aware, the way you are doing it, allows for any user to delete any comment by entering its id, this is not safe!

update MySQL using PHP

Dear friends i am not an expert in php and need your help to solve an issue.
I am trying to create a page where i can call data from MySql and can edit/update it. The first part to display the data is done but i am unable to update it ... friends kindly help me solve this.
function Get_pages($mysql) {
$PageQuery = $mysql->query("SELECT * FROM pages WHERE PageID = '$pageID'");
while (($row = $PageQuery->fetch_assoc()) !== null)
{
echo '<form action="page.php" method="post">';
echo '<span class="lbl">Page Title</span>';
echo '<input name="PageTitle" type="text" value="' . $row["PageTitle"] . '" />';
echo '<span class="lbl">Page Content</span>';
echo '<textarea class="txt-area" name="PageContent" cols="" rows="18">' . $row["PageContent"] . '</textarea>';
echo '<input name="UpdateBtn" value="Update Page" type="submit" class="submit_btn"></form>';
}
// WHEN BUTTON CLICKED
if ($_REQUEST['UpdateBtn'])
{
$pageID = $_REQUEST["$pageID"];
$PageTitle = addslashes($_REQUEST['PageTitle']);
$PageContent = addslashes($_REQUEST['PageContent']);
$sql = mysql_query ("UPDATE pages SET PageTitle='$PageTitle', PageContent='$PageContent' WHERE pageID='$pageID'") or die ("Not Updating");
}
}
$sql = mysql_query ("UPDATE
should be
$sql = $mysql->query("UPDATE
You are making connection with mysqli_* function and using mysql_* function for update , because of that your UPDATE is failing.

`while` is not showing the echo in php

I'm creating a small private forum to get some more knowledge about PHP/PDO etc. Now I have a weird bug/error/wrong piece of code that is not showing the echo. This is my code.
$sql2 = $db->prepare('SELECT topic_id, topic_subject,topic_date,topic_cat FROM topics WHERE topic_cat = :topid');
$sql2->bindParam(':topid', $_GET['id'], PDO::PARAM_INT);
$sql2->execute();
$result2 = $sql->rowCount();
if($result2 === FALSE){
echo 'The topics could not be displayed, please try again later.';
}
elseif ($result2 === 0){
echo 'There are no topics in this category yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = $sql2->fetch()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
It should show the echo at while($row = $sql2->fetch()), but it is not. Also I know there is not enough { and } but that's because the other part of the code is not relevant.
You appear to count the rows returned by $sql then loop through $sql2. Have you checked to see if there are any results in $sql2?

Categories