DELETE row entry from database - php

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

Related

How to fix Warning: Invalid argument supplied for foreach()

I'm setting an edit user page on my local machine using PHP. There is this error
Warning: Invalid argument supplied for foreach() on line 79(<?php foreach ($user as $key => $value) : ?>)
I have tried to solve it, but in vain. I'm kinda new to PHP. Maybe there is something that I am missing or not seeing. Kindly assist and correct me if need be. Below is my code from the update.php page.
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
include_once 'core/init.php';
require 'common.php'; //Escapes HTML for output
if (isset($_POST['submit'])) {
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$user = [
"id" => $_POST['id'],
"username" => $_POST['username'],
"email" => $_POST['email'],
"join_date" => $_POST['join_date']
];
$DB->query ('UPDATE users
SET id = :id,
username = :username,
email = :email,
join_date = :join_date
WHERE id = :id');
$DB->execute();
}
catch(PDOException $e){
echo $this->error = $e->getMessage();
}
}
if (isset($_GET['id'])) {
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$id = $_GET['id'];
$DB->query('SELECT * FROM users WHERE id = :id');
$DB->bind(':id', $id);
$DB->execute();
$result=$DB->resultset();
// Catch any errors
}
catch(PDOException $e){
echo $this->error = $e->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $DB) : ?>
<blockquote><?php echo escape($_POST['username']); ?> successfully updated.</blockquote>
<?php endif; ?>
<h2>Edit a user</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?></label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?> >
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
You are not setting any value for initial loading for variable $user, so it is undefined in foreach, so either use
$user = [];
if (isset($_POST['submit'])) {
try{
Or check and set value for $user
<?php foreach ($user ?? [] as $key => $value) : ?>

display multiple results from a sql query

so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>

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!

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

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