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

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();
}
?>

Related

php - form submit button doesn't work

I want to do simple CRUD operations. I created a form for this and I am doing data entry. but when I refresh the page it automatically registers itself. I tried to solve this logic error with the "isset" function, but it did not. where can the error be?
$ad = isset($_POST['ad']) ? $_POST['ad'] : '';
$soyad = isset($_POST['soyad']) ? $_POST['soyad'] : '';
$adres = isset($_POST['adres']) ? $_POST['adres'] : '';
$tur = isset($_POST['tur']) ? $_POST['tur'] : '';
if(isset($_POST["submit"])){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// bağlantı özelliklerinden hata modunu aktifleştirdik
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `kisiler` (`ad`, `soyad`, `adres`, `tur`) VALUES ('$ad', '$soyad', '$adres', '$tur')";
// use exec() because no results are returned
$conn->exec($sql);
echo "işte şimdi oldu";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
<html>
<body>
<form action="" method="POST">
<p>
Ad: <input type="text" name="ad"/>
Soyad: <input type="text" name="soyad"/>
Adres:<input type="text" name="adres"/>
Tur: <input type="text" name="tur"/>
<input type="submit"name="submit"/>
</p>
</form>
</body>

minichat in php not saving or showing any texts etc [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
Hey i want to create a minichat just as exercise but for some reason it A) goes to a seperate page after i hit Send and doesnt return and B) does NOT post anything nor does it save anything to the database. Minichat form his here:
<!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=minichat', '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>
Here is the Post form:
<?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.php');
?>
in my PHP DB i got a 2 fields, username and message, i added a new one saying ID but that did not help either.
You missed a closing ')' in INSERT query. Change this line
$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
to
$req = $bdd->prepare('INSERT INTO minichat (username, message) VALUES (?, ?)');

No result from fetchAll();

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']);

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