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) : ?>
Related
I am making a panel with PHP. It contains a login script. It's working good, just what I expect. The next step is: Echo the username.
With $_POST you can echo the username what the person has typed. So, just like: Welcome, $username.
The problem now is, that I can't echo the $_POST. It's not possible because you will redirect to another page. My question is: How can I echo a username.
My login script:
<?php
//DATABASE CONNECTION
session_start();
$host = "localhost";
$username = "root";
$password = "root";
$database = "test_tutorial";
$message = "";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $_POST["fname"];
//LOGIN CHECK
if(isset($_POST["login"])) {
if(empty($_POST["fname"]) || empty($_POST["lname"])) {
echo 'All fields required';
}
else
{
$query = "SELECT * FROM users WHERE fname = :fname AND lname = :lname";
$statement = $connect->prepare($query);
$statement->execute(
array(
'fname' => $_POST["fname"],
'lname' => $_POST["lname"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
//VISITED
header("Refresh:0; url=veilig.php");
//END
}
else
{
echo 'Wrong data';
}
}
}
}
catch(PDOException $error) {
$message = $error->getMessage();
}
?>
My form:
<form action="" method="post">
<label>fname</label>
<input type="text" name="fname" class="form-control" />
<br />
<label>lname</label>
<input type="password" name="lname" class="form-control" />
<br />
<input type="submit" name="login" value="Login" />
</form>
So, how can I echo a post if someone is redirected to another page?
You've already called session_start so you're ready to use the $_SESSION superglobal which will persist data for the user across all pages that call session_start first.
For example, here on index.php
<?php
session_start();
$_SESSION['username'] = 'Prabhjot.Singh';
header('Location: veilig.php');
Then later on veilig.php
<?php
session_start();
echo $_SESSION['username'];
Prabhjot.Singh
<?php
$dsn = '';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
require 'mysqli_connect.php';
if(isset($_POST['submit']) && !empty($_POST['submit'])){
$sth = $dbh->prepare('INSERT INTO test_table(comment) VALUES(?);');
$comment = $_POST['comment'];
$sth->execute(Array($comment));
}
?>
the code below will refresh the page, but not post to my database (nor will REQUEST_URI). If I put the actual php form name in place of the <?php echo htmlspecialchars($_SERVER['PHP_SELF']);?> it works fine. I have tried double quotes, single quotes, and everything in between. What's up with this not working?
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post">
<p>Comment</p>
<textarea name= "comment" rows="6" cols="50"></textarea><br />
<input type="submit" name= "submit" value="submit" id = "submit">
</form>
<?php
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$Name = $_POST['Name'];
$Password = $_POST['Password'];
$message ="";
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE Name='$Name' and Password='$Password'");
$stmt->execute();
$result = $stmt->fetchcolumn();
if($result > 0)
{
$_SESSION['Logged In'] = $Name;
$_SESSION['Logged In'] = $Password;
if(isset($_SESSION['Logged In']))
{
echo $result;
session_start();
header('Location: Main.php');
exit();
}
}
elseif($result == 0)
{
echo $result;
echo "Invalid Username or Password";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$conn = null;
}
?>
i need help with this simple login system if i comment out the header redirect the echo result shows i am only getting 1 result as expected when i put the redirect in the page just refreshes instead of going to the next page.
There are a few simple issues in this code
First you must start the session before you do anything with it. In fact its best to start it at the top of every script before doing anything else.
Also because you have echoed something to the browser before you have run the header, this will be a probelm. Headers have to be sent before any page data.
Also your code is liable to SQL Injection so use prepared and parameterised queries to avoid this.
You also appear to be storing a plain text password in the database. another big No No
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
If you are using a PHP version prior to 5.5 there is a compatibility pack available here
<?php
session_start();
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stmt = $conn->prepare("SELECT Password
FROM user
WHERE Name=:name");
$params = array(':name'=>$_POST['Name'])
$stmt->execute($params);
$hashedPassword = $stmt->fetchcolumn();
if(password_verify($_POST['Password'], $hashedPassword) ) {
$_SESSION['Logged In'] = $_POST['Name'];
// bad idea putting password in a session
//$_SESSION['Logged In'] = $Password;
// you just set this data so the if is unnecessary
//if(isset($_SESSION['Logged In'])) {
// cannot echo anything before doing a header()
// any way if the header works you wont see this data
// anyway as a new page will be being loaded
//echo $result;
header('Location: Main.php');
exit;
} else {
echo $result;
echo "Invalid Username or Password";
}
catch(PDOException $e) {
echo $e->getMessage();
}
$conn = null;
}
?>
As this now uses a hashed password, you will have to recreate your users and when tou do, use
$passwordToPutOnDatabase = password_hash($thepassword);
There are may issues with your code, you are storing passwords in plain text which is completely wrong, you should use password_hash() and password_verify()
I have made you a simple login/register script which will show you how to use the password_hash and password_verify()
simple_register.php
<?php
require 'db_config.php';
if(isset($_POST['register'])){
//validate email and password I'm not gonna do that for you
$password = $_POST['upass']; // when u done with validation
$email = $_POST['username'];
$hash = password_hash($password,PASSWORD_DEFAULT); //hash password
try {
$stmt = $conn->prepare("INSERT INTO users (username,password) VALUES ( ?,?)");
if($stmt->execute(array($email,$hash))){
echo "user registered";
}else{
echo "could not register"; // something wrong with your query check error log
}
} catch (Exception $e) {
error_log($e->getMessage());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple PDO Registration</title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><input type="email" name="username" placeholder="Enter your email"></p>
<p><input type="password" name="upass" placeholder="Enter password"></p>
<button type="submit" name="register">Register</button>
</form>
</body>
</html>
login.php
<?php
ob_start();
session_start();
require 'db_config.php';
if (isset($_SESSION['loggedin'])) {
header("location:users/dashboard.php");
} else {
$loginMessage = "";
$msg_class = "";
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['upass'])) {
$loginMessage = "Enter username and password";
$msg_class = "error";
} else {
$username = $_POST['email'];
$password = $_POST['upass'];
try {
$stmt = $conn->prepare("SELECT userID,username,password FROM users where username = ? ");
$stmt->execute([$username]);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row):
if (password_verify($password, $row['UserPassword'])) {
$_SESSION['loggedin'] = $row['userID'];
$loginMessage = "Login Successfully! Redirecting...";
$msg_class = "success";
header("refresh:5; url=dashboard");
} else {
$loginMessage = "Password and username does not match";
$msg_class = "error";
}
endforeach;
} else {
$loginMessage = "Invalid username";
}
}
catch (PDOException $e) {
error_log($e);
}
}
}
}
?>
</head>
<body>
<div id="main">
<h1>User Login</h1>
<div class="row">
<div class="large-6 columns large-centered" id="box">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<label>Email</label>
<input type="text" name="email" class="input" >
<label>Password </label>
<input type="password" name="upass" class="input" id="password"/><br/>
<div class="large-6 columns pull-2">Forgot Password</div>
<button type="submit" class="button" name="login" disabled="true" id="long">Login</button>
<div class="<?php echo $msg_class;?>">
<?php
echo $loginMessage;
?>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#password').keyup(function(e){
$('#long').prop('disabled', false);
});
});
</script>
</div>
db_config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "samedicalspecialists";
try {
$conn= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
error_log($e);
}
?>
I am trying to delete a row from a table using PHP (PDO) on a page listing the rows entered into the database. I've been tinkering with the delete.php code to try to make it work but to no avail. I appreciate any help.
Below is my code:
listview.php
session_start();
include_once('../includes/connection.php');
include_once('../includes/events.php');
$event = new Event;
$events =$event->fetch_all();
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to the admin page</title>
</head>
<body>
<div class="container">
<h1>The List of Events</h1>
<ol>
<?php foreach ($events as $event) { ?>
<li>
<?php echo $event['event_name']; ?>
<?php echo $event['event_date']; ?>
<?php echo $event['event_location']; ?>
<?php echo $event['description']; ?>
<?php echo $event['start_time']; ?>
<?php echo $event['end_time']; ?>
<?php echo $event['poc_name']; ?>
<?php echo $event['poc_email']; ?>
<?php echo $event['poc_number']; ?>
<!--edit/delete links-->
Edit
Delete
<!--end edit/delete links-->
</li>
<?php } ?>
</ol>
</div>
</body>
</html>
<?php
} else {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//check the fields in the login form
if(empty($username) or empty($password)) {
$error = 'All fields are required';
} else {
$query = $dbh->prepare("SELECT * FROM admin WHERE username = ? AND userpassword = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//correct
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//incorrect
$error = 'Incorect details';
}
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Squeegee Admin Login</title>
</head>
<body>
<div class="container">
Squeegee Admin
<br/>
<?php if (isset($error)) { ?>
<small style="color:#aa000; "><?php echo $error; ?> </small>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php } ?>
Connection
<?php
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=squeegee", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
events.php
<?php
class Event {
//queries from database
public function fetch_all() {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events");
$query->execute();
return $query->fetchAll();
}
//queries specific article via id
public function fetch_data($event_id) {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events WHERE event_id = ? ");
$query->bindValue(1, $event_id);
$query->execute();
return $query->fetch();
}
}
?>
delete.php
<?php
include('../includes/connection.php');
$event_id=$_GET['event_id'];
$result = $dbh->prepare("DELETE FROM events WHERE event_id= :event_id");
$result->bindParam(':event_id', $event_id);
$result->execute();
header("location: index.php");
?>
As your question stands, it seems you're accessing the wrong index.
In your link it is defined as id:
Delete
// ^
But then accessed in your PHP file as:
$event_id=$_GET['event_id'];
Must be: $event_id = $_GET['id'];
Either you change your url as ?event_id in the anchor or change the array index in your PHP $event_id = $_GET['id'];. The important things is they must match.
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']);
}