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();
}
Related
This question already has answers here:
PHPStorm: undefined variables caused by include/require
(6 answers)
Closed last year.
This is my index file,
<?php
include 'db.php';
$form = read('form');
//echo '<pre>';
//print_r($forms);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="store.php" method="post">
<label>
Username:
<input type="text" placeholder="username" name="username">
</label>
<label>
Password:
<input type="text" placeholder="password" name="password">
</label>
<label>
Email:
<input type="text" placeholder="email" name="email">
</label>
<button type="submit" name="submit">
submit
</button>
</form>
<table>
<?php foreach ($form as $user): ?>
<tr>
<?php foreach ($user as $item) {
echo '<td>' . $item . '</td>';
} ?>
</tr>
<?php endforeach; ?>
</table>
</body>
and this is my db connection file that reads the database:
<?php
$servername = "localhost";
$username = "root";
$password = "mhimlaA#1";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function read($where = '')
{
global $conn;
$sql = "SELECT * FROM `form` $where LIMIT 1000;";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll(PDO::FETCH_ASSOC);
}
I have weird problem in here that PhpStorm shows an error on $conn in the store file. I'm using this file to insert the input text to database:
<?php
print_r($_POST);
unset($_POST['submit']);
include 'db.php';
$form = read('form');
$sql = "INSERT INTO mydb.form(username, password, email) VALUES (:username,:password,:email)";
$stm = $conn->prepare($sql);
$stm->execute($_POST) or die($conn->errorInfo());
header('location: index.php');
PHPStorm is correct. $conn can be undefined if there was a problem connecting to the database. The actual issue is your poor error handling. Never try-catch exceptions if you don't know what to do with them. You are following cargo cult.
You need to either remove the try-catch or throw an exception in the catch block if you really want to prevent credential leak in error logs.
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected successfully";
} catch (PDOException $e) {
throw new \PDOException($e->getMessage(), (int) $e->getCode());
}
You should also remove useless bits of code such as or die($conn->errorInfo())
I'm trying to create a delete function starting from this link
<a href="videogamedatabaseadduserlist.php?function=delete&IndEMail='.$_POST['IndEMail'].'&IdGame='.$row['IdGame'].'">Elimina<a>'.'<BR>'
and this is the php it should interact with
if ($_GET['function']== 'delete'){
$conn = new PDO('mysql:host=localhost;dbname=videogamelist', 'root', 'root',array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$sql = "delete from lists where IndEmail = :IndEmail and IdGame = :IdGame";
$res_prepare = $conn->prepare($sql);
$res_prepare->bindParam(':IdGame',$_GET['IdGame']);
$res_prepare->bindParam(':IndEmail',$_GET['IndEmail']);
$a=$res_prepare->execute();
echo "Gioco cancellato";
}
After many try and searching on this site i can't find the reason the query doesn't work.
i tested and it worked! if this doesn't work for you, check db or form
try {
$conn = new PDO("mysql:host=localhost;dbname=videogamelist", 'root', 'root');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);;
$sql = "DELETE FROM lists WHERE IndEmail = :IndEmail AND IdGame = :IdGame";
$res_prepare = $conn->prepare($sql);
$res_prepare->bindParam(':IdGame', $_GET['IdGame'], PDO::PARAM_INT);
$res_prepare->bindParam(':IndEmail',$_GET['IndEmail'], PDO::PARAM_INT);
$res_prepare->execute();
echo "Deleted";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
not sure where $row['IdGame'] is coming from so i'm using basic form just to test the code:
<form name="delete" action="test.php" method="get">
<input type="text" name="IdGame">
<input type="text" name="IndEmail">
<input type="submit" name="delete" value="delete" >
</form>
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();
}
?>
I have an update form which I am trying to enable updating fields but struggling to update the fields when submitting - perhaps I am missing something very obvious here.
Here is my form:
<form action="actions/updateDoc.php" method="POST">
<input type="text" value="<?php echo $doc['doc_title'] ?>" name="doc_title" />
<br />
<input type="submit" value="Update" name="submit" />
</form>
Here is the script to action that form:
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='******';
$password='******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$doc_title = $_POST['doc_title'];
$sql = "UPDATE doc_list (doc_title) SET ('".$_POST["doc_title"]."')";
if ($dbh->query($sql)) {
header ('Location: ../docEdit.php');
}
else{
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
The script runs but getting a blank screen and no update occurs. I have now taken some code out to show just updating 1 row, I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(doc_title) SET ('Document content sdfsd')' at line 1
First, add the doc_id to your form (as a hidden input) -
<form action="actions/updateDoc.php" method="POST">
<input type="text" value="<?php echo $doc['doc_title'] ?>" name="doc_title" />
<input type="hidden" value="<?php echo $doc['doc_id'] ?>" name="doc_id" />
<br />
<input type="submit" value="Update" name="submit" />
</form>
Then change your php code to get the doc_id (and use prepared statement/placeholders) -
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='******';
$password='******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "UPDATE doc_list SET doc_title = :doc_title WHERE doc_id = :doc_id";
$query = $dbh->prepare($sql);
$query->execute(array(":doc_title"=>$_POST["doc_title"], ":doc_id"=> $_POST["doc_id"]));
if ($query) {
header ('Location: ../docEdit.php');
}
else{
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
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']);