No result from fetchAll(); - php

I'm totally a newbie in the world of PHP and MySQL. I am reading the book of Kevin Yank and while doing one of his examples, I encountered a weird outcome. I'm sure I followed and typed correctly the code written on his book but I wondered why I'm not getting the same result. I've checked the code back and forth and sure that it is right or maybe I'm missing something.
I'm posting this here because I know a lot from here are very helpful and very kind to starters like me. Any inputs are highly appreciated. Looking forward for comments so that I can proceed with my studies because I think I am stuck because of this weird error.
Please see below code for your reference.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Joke CMS</title>
</head>
<body>
<h1>Joke Management System</h1>
<ul>
<li>Manage Jokes</li>
<li>Manage Authors</li>
<li>Manage Joke Categories</li>
</ul>
</body>
</html>
index.php
<?php
//Display author list
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try {
$result = $pdo->query('SELECT id, name FROM author');
} catch (PDOException $e){
$error = 'Error fetching authors from database! ' . $e->getMessage();
include 'error.html.php';
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'Delete')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
//Get jokes belonging to author
try {
$sql = 'SELECT id FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e){
$error = 'Error fetching authors with their jokes! ' . $e->getMessage();
include 'error.html.php';
exit();
}
$result = $s->fetchAll();
//Delete joke category entries
try {
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
//For each joke
foreach ($result as $row)
{
$jokeId = $row['id'];
$s->bindValue(':id', $jokeId);
$s->execute();
}
} catch (PDOException $e){
$error = 'Error deleting joke category! ' . $e->getMessage();
include 'error.html.php';
exit();
}
//Delete jokes belonging to author
try {
$sql = 'DELETE FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e){
$error = 'Error deleting joke from a specific author! ' . $e->getMessage();
include 'error.html.php';
exit();
}
//Delete the author
try {
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e){
$error = 'Error deleting the author from database! ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
foreach ($result as $row){
$authors[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
include 'authors.html.php';
?>
authors.html.php
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helper.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Manage Authors</title>
</head>
<body>
<h1>Manage Authors</h1>
<p>Add new author</p>
<ul>
<?php foreach($authors as $author): ?>
<li>
<form action="" method="post">
<div>
<?php echo htmlout($author['name']); ?>
<input type="hidden" value="<?php echo htmlout($author['id']); ?>"/>
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Delete"/>
</div>
</form>
</li>
<?php endforeach; ?>
</ul>
<p>Return to JMS home</p>
</body>
</html>
All inputs are highly apprecited.

I'm not gonna ask if the $pdo object is properly initialized and if you have actual records in the database. You test queries with an external MySQL client like Workbench. You use it to optimize too. Only when you are satisfied with a query, you put it in your script, unless it's so simple you can write it properly in place.
Escape `table_names` and `column_names` to be MySQL legit and also end queries with a ;. And it looks better.
Also, before foreach initialize the variable $authors = array();. That book should teach you that.
Learn to use var_dump(). Put var_dump($result); after $result = $pdo->query('...');. Also use var_dump($row); in the foreach. It's used for simple but effective debugging. Prints variable values.
htmlout() does exist?
What do you actually see after the var_dump()s added around?

In your authors.html.php file, you didn't give your hidden input type a name
<input type="hidden" value="<?php echo htmlout($author['id']); ?>"/>
try changing to
<input type="hidden" name="id" value="<?php echo htmlout($author['id']); ?>"/>
Your are looking for a POST variable which doesn't exist
$s->bindValue(':id', $_POST['id']);

Related

Form is not posting to MySQL database

I am trying to send data from a textfield to my database. When I run the code I get no errors. But the code isnt posting the data to the database. I cant see whats wrong, can someone look what is wrong?
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<button name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
$data_1 = $_POST['data_1'] ;
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>
a) your script needs more error handling.
Before accessing $_POST['data_1'], you should test its existence, e.g. via isset().
Your database code doesn't have any error handling, too. Either set the error mode to PDO::ERRMODE_EXCEPTION or (/and) make sure you test each and every return value of the PDO::* methods.
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
if ( !$stmt ) {
yourErrorHandler('could not prepare statement', $db->error);
}
else if ( !$stmt->execute(array($adres_1)) ) {
yourErrorHandler('could execute statement', $stmt->error);
}
else if ( 1>$stmt->rowCount() ) {
// no record has been updates
}
else {
// at least one record has been updated
}
b) $stmt->execute(array($adres_1)); What is $adres_1? It's not anywhere else in that code.
c) Your code is prone to sql injections. You can fix that e.g. by using prepared statements + parameters.
The whole code looks like small parts of other scripts have been copy&pasted without understanding what those snippets do.
Are you using autocommit? maybe your db changes are being rolled back. Try adding an extra COMMIT SQL statement.
You have to submit your code. Then only the values are send to the php file by the POST method.
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<input type="submit" name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
if ($_POST['send']) {
$data_1 = $_POST['data_1'] ;
}
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>

Fatal error: Call to undefined method PDO::error()

apparently this works for my teacher but for me it gives the error Fatal error: Call to undefined method PDO::error()
Code in Question:
<!DOCTYPE html>
<html>
<head>
<title>Mini-Chat</title>
<meta charset="UTF-8">
<style>
form
{
text-align: center;
}
</style>
<body>
<form action="minichat-post.php" method ="post">
<p>
<label for="username">Username</label> : <input type="text" name="username" id="username"/><br>
<label for="message">Message</label> : <input type="text" name="message" id="message"/><br>
<input type="submit" value="Send"/>
</p>
</form>
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
?>
</body>
</html>
more specifically it gives me the error line 31 which is the while loop:
while ($data = $response->fetch())
going nuts here as it worked once already with a small correction but now i cant seem to find out where to make it.
EDIT: Error is now away but it wont save any messages in the database nor display them after hitting Send.
here the post php file:
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=minichat', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
$req->execute(array($_POST['username'], $_POST['message']));
header('Location: ./mini-chat[conflit].php');
?>
add this
fetch(PDO::FETCH_ASSOC);
in here
fetch()
PDOStatement::fetch
Also check for post
<?php
if(isset($_POST['username']) && isset($_POST['message'])) {
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
}
?>

When user hits the submit button, index.php does not catch the action and update database

I have 3 files here, index.php, authors.html.php and form.html.php, index.php is my controller script that then calls authors.html.php to display the authors and finally form.html.php when a user wants to edit an author or add an author in a MySQL database.
The problem I run into is that when the user hits the update button, the database does not get update the author details... it seems my controller script is not catching the 'editform' action? I'm no entirely sure why it's slipping. Here are excerpts from the files:
index.php (controller):
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
if ((isset($_POST['action'])) and ($_POST['action'] == 'Edit'))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; //connect to mysql
try
{
$sql = 'SELECT id, name, email FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching author details...';
include 'error.html.php';
exit();
}
$row = $s->fetch();
$pageTitle = 'Edit Author';
$action = 'editform';
$name = $row['name'];
$email = $row['email'];
$id = $row['id'];
$button = 'Update Author';
include 'form.html.php';
header('Location: .');
exit();
}
if (isset($_GET['editform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; //connect to mysql
try
{
$sql = 'UPDATE author SET name = :name, email = :email WHERE id = :id';
$s->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->bindValue(':name', $_POST['name']);
$s->bindValue(':email', $_POST['email']);
$s->execute();
}
catch (PDOException $e)
{
$error = "Error updating selected author.";
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try
{
$result = $pdo->query('SELECT id, name FROM author');
}
catch (PDOException $e)
{
$error = 'Error fetching authors from the database: ';
include 'error.html.php';
exit();
}
foreach($result as $row)
{
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php';
?>
authors.html.php
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php' ?>
// When I call "htmlout()" is the same as "echo htmlspecialchars()"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Authors</title>
</head>
<body>
<p>
<h1>Manage Authors</h1>
<p>
Add New Author
</p>
<ul>
<?php foreach ($authors as $author): ?>
<li>
<form action="?<?php $action ?>" method="post">
<div>
<?php htmlout($author['name']); ?>
<input type="hidden" name="id" value="<?php echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</li>
<?php endforeach; ?>
</ul>
<p>
Return to JMS Home
</p>
</p>
</body>
</html>
form.html.php
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php htmlout($pageTitle); ?></title>
</head>
<body>
<h1><?php htmlout($pageTitle); ?></h1>
<form action="?<?php $action ?>" method="post">
<div>
<label for="name">Name:
<input type="text" name="name" id="name" value="<?php htmlout($name); ?>">
</label>
</div>
<div>
<label for="email">Email:
<input type="text" name="email" id="email" value="<?php htmlout($email); ?>">
</label>
</div>
<div>
<input type="hidden" name="id" value="<?php htmlout($id); ?>">
<input type="submit" name="action" value="<?php htmlout($button) ?>">
</div>
</form>
</body>
</html>
I found out what I did wrong! Phew...
I screwed up on this line
$s->prepare($sql);
it should have been
$s = $pdo->prepare($sql);
and as #MamaWalter pointed out, I was looking at $_GET for a $_POST variable, so I changed that it it's now working great!
#linus72982 Your suggestion to use var_dump() was a tremendous help, I am new to PHP and thus did not know about it... thanks again for everything!

DELETE row entry from database

Good day!
I am totally new to PHP and would appreciate any help coming from you.
I want to delete a row in a database but I got this error:
Warning: Illegal string offset 'text' in C:\xampp\htdocs\php\deletejoke\jokes.php on line 14
The code seem okay but I don't know why I'm getting this error.Please guide me to this, thanks a lot!
Please see below the code for your reference:
if (isset($_GET['deletejoke'])) {
try {
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error = 'Error deleting joke' . $e->getMessage();
include 'error.php';
exit();
}
header('Location: .');
exit();
}
try {
$sql = 'SELECT id, joketext FROM joke';
$result = $pdo->query($sql);
} catch (PDOException $e) {
$error = 'Error fetching jokes' . $e->getMessage();
include 'error.php';
exit();
}
foreach ($result as $row) {
$jokes = array('id' => $row['id'], 'text' => $row['joketext']);
}
include 'jokes.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise #3: Display contents from database</title>
<meta charset="utf-8"/>
</head>
<body>
Add your own joke!
<p>Here are all the jokes in the database:</p>
<?php foreach($jokes as $joke): ?>
<form action="?deletejoke" method="post">
<blockquote>
<p>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>
<input type="hidden" name="id" value="<?php echo $joke['id']; ?>">
<input type="submit" value="Delete">
</p>
</blockquote>
</form>
<?php endforeach; ?>
</body>
</html>
The Warning is telling you that it is treating $jokes, and therefore $joke as a string and not an array.
Try building your $jokes array like this
// initialize the array
$jokes = array();
foreach ($result as $row) {
// add to the array using $jokes[]
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}

PHP Forms to update a SQLite3 database

I need some help I am trying to create a PHP form using sqlite3 and I keep on getting a "syntax error, unexpected T_CATCH in post.php on line 10". All I want to do from the php form is update an existing sqlite3 database in the table1 where the column type = p and the column id = 340 with the values from the form.
HTML Code:
<html>
<head>
<title>Update Form</title>
</head>
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
Slot1: <input type="text" name="slot1"><br>
Slot2: <input type="text" name="slot2"><br>
</p>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
$slot2 = sqlite_escape_string($_POST['slot2']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(Exception $e)
{
echo $e->getMessage();
}
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE tabel1 SET Slot1Pos = :slot1, Slot2Pos = :slot2 WHERE Type = P and ID = 340");
$stmt->bindParam(':slot1', $slot1, PDO::PARAM_STR);
$stmt->bindParam(':slot2', $slot2, PDO::PARAM_STR);
$stmt->execute()
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "Form submitted successfully";
}
Looks like you're missing a brace:
try {
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo $e->getMessage();
}

Categories