I have been playing around with editing user profiles (Logged in as) which is working just fine.
So I decided to try editing other users profiles by populating a table with users (which works fine and also has, ban & delete working fine), clicking a hyperlink with id (which works fine), showing the username of the profile and their current profile info(which works fine) and a form to update which is identical to the edit session user form(also, works fine).
But when submitting, it does not update the record.
I am using $userID = $_GET['id']; and also binding that to sql select id command.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$userID = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$userID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['update'])) {
$location = isset($_POST['location']) ? $_POST['location'] : null;
$about = isset($_POST['about']) ? $_POST['about'] : null;
$title = isset($_POST['title']) ? $_POST['title'] : null;
$sql_part = array();
$prepare = array();
if ($location) {
$sql_part[] = 'location = :location';
$prepare[':location'] = $location;
}
if ($about) {
$sql_part[] = 'about = :about';
$prepare[':about'] = $about;
}
if ($title) {
$sql_part[] = 'title = :title';
$prepare[':title'] = $title;
}
$prepare[':id'] = $userID;
if (count($sql_part)) {
$sql = 'UPDATE users SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE id = :id';
$stmt = $conn->prepare($sql);
if ($stmt) {
$result = $stmt->execute($prepare);
$count = $stmt->rowCount();
header('Location: '. $_SERVER['REQUEST_URI']);
exit;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit <?php echo ($userRow['username']); ?>'s Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
Related
I will describe my problems briefly. There are 2 main issues in my web app:
Date of Birth does not show in the edit page (DONE)
I cannot submit my record to the database (partly due to problem 1)
Here is my code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "students";
$mysqli = new mysqli($host, $username, $password, $database);
if (!$mysqli) {
die("Cannot connect to mysql");
}
if (isset($_POST['save'])) {
// Display errors if all fields are blank
$errors = [];
if (strlen(trim($_POST['student_id'])) === 0) {
$errors['student_id'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['first_name'])) === 0) {
$errors['first_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['last_name'])) === 0) {
$errors['last_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['email'])) === 0) {
$errors['email'] = "Không được để trống trường này";
} else {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email phải đúng định dạng';
}
}
if (strlen(trim($_POST['dob'])) === 0) {
$errors['dob'] = "Không được để trống trường này";
}
}
// If there is not any black field, show the information at the index page
$id = $_GET['id'];
$sql = "SELECT * FROM students WHERE id = $id";
$result = $mysqli->query($sql);
$students = $result->fetch_assoc();
print_r($students) ;
if (isset($errors) && count($errors) == 0) {
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$sql = "UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'";
$result = $mysqli->query($sql);
if ($result) {
header('location: index.php');
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Student List</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
<body>
<div class="card">
<div class="card-body">
<h3 class="card-title">Create Student</h3>
<form method="POST" action="./update.php" id="update">
<!-- Student ID -->
<div class="form-group">
<label for="student_id">Student ID <span style="color:red;">*</span></label>
<input type="text" id="student_id" name="student_id" class="form-control <?php echo isset($errors['student_id']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['student_id'] ?>">
<?php if (isset($errors) && isset($errors['student_id'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['student_id']; ?></small>
<?php } ?>
</div>
<!-- First Name -->
<div class="form-group">
<label for="first_name">First Name <span style="color:red;">*</span></label>
<input type="text" id="first_name" name="first_name" class="form-control <?php echo isset($errors['first_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['first_name'] ?> ">
<?php if (isset($errors) && isset($errors['first_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['first_name']; ?></small>
<?php } ?>
</div>
<!-- Last Name -->
<div class="form-group">
<label for="last_name">Last name <span style="color:red;">*</span></label>
<input type="text" id="last_name" name="last_name" class="form-control <?php echo isset($errors['last_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['last_name'] ?>">
<?php if (isset($errors) && isset($errors['last_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['last_name']; ?></small>
<?php } ?>
</div>
<!-- Email -->
<div class="form-group">
<label for="email">Email <span style="color:red;">*</span></label>
<input type="email" id="email" name="email" class="form-control <?php echo isset($errors['email']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['email'] ?> ">
<?php if (isset($errors) && isset($errors['email'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['email']; ?></small>
<?php } ?>
</div>
<!-- Date of Birth -->
<div class="form-group">
<label for="dob">Date of Birth <span style="color:red;">*</span></label>
<input type="date" id="dob" name="dob" class="form-control <?php echo isset($errors['dob']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['dob'] ?> ">
<?php if (isset($errors) && isset($errors['dob'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['dob']; ?></small>
<?php } ?>
</div>
<!-- Buttons -->
<button type="submit" class="btn btn-primary" name="save">Save</button>
<a class="btn btn-secondary" href="./index.php">Cancel</a>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
Here is some pictures about those:
Hopefully, you can help me solve those problems as much as possible. Thank you!
The date of birth issue: extra space at the end of your value tag
value="<?php echo $students['dob'] ?> "
The database issues:
malformed update statement
insecure, open-to-attack query
You kind of mixed insert and update.
UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'
Update statements don't take a field list in parens like you have it.
So the statement is failing. However you should really protect again SQL injection attacks by using query binding and prepared statements. Looks like this:
$sql = "UPDATE students SET student_id = '?', first_name = '?', last_name = '?', email = '?', dob = '?' WHERE id = '?'";
$query = $mysqli->prepare($sql);
$query->bind_param("isssi", $student_id, $first_name, $last_name, $email, $dob, $id);
$query->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :
I need help, the problem is that I have a input page (the modified user profile)
where I have a section of addresses and I need to do a loop where each group of inputs I put the information of each of the directions.
Because now for example if I have 3 directions, in the 3 groups of inputs I get the same repeated information...
Here is a part of the code, I don't put all it because is too large, I only put the important code of this issue.
Thanks to all :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="font-awesome-4.5.0/css/font-awesome.min.css"/>
<link href="css/css.css" rel="stylesheet" type="text/css" media="all" />
<link rel="stylesheet" type="text/css" href="css/icSquared_v1.0.css"/>
<title>Modificación de Direcciones</title>
</head>
<body>
<div>
<?php
include 'fn.php';
iniciarSesion();
$email = $_SESSION['user'];
$conexion = conectar();
$sql = "SELECT * FROM DIRECCION WHERE email_c='".$email."'";
if($resultado = $conexion -> query($sql)){
while($fila = mysqli_fetch_array($resultado)){
$ide = $fila[0];
$via = $fila[1];
$nombre = $fila[2];
$numero = $fila[3];
$piso = $fila[4];
$poblacion = $fila[6];
$direcciones = mysqli_num_rows($resultado);
desconectar($conexion);
$sql = "SELECT * FROM POBLACION WHERE idPoblacion='".$poblacion."'";
$conexion = conectar();
if($resultado = $conexion -> query($sql)){
if($fila = mysqli_fetch_array($resultado)){
$codigoPostal = $fila[1];
$nombrePob = $fila[2];
$comunidad = $fila[3];
$pais = $fila[5];
desconectar($conexion);
}
}else{
desconectar($conexion);
}
}else{
deconectar($conexion);
}
?>
<div class="col-sm-8">
<div id="admin_centro" style="margin-top:2%">
<form action="action.php?accion=updateCenterDir" method="post">
<?php for($i=0; $i<$direcciones; $i++){ ?>
<div class="col-sm-2" style="margin:2% 6% 0 5%;">
<div class="form-group">
<input type="hidden" name="ide" value="<?php echo $ide; ?>" />
<h4 class="text-success text-right">Dirección <?php echo $i+1 ?></h4>
<label>Tipo de via:</label>
<input type="text" name="via" class="form-control" value="<?php echo $via; ?>" required />
</div>
<div class="form-group">
<label>Nombre: </label>
<input type="text" name="nombre" class="form-control" value="<?php echo $nombre; ?>" required />
</div>
<div class="form-group">
<label>Numero: <label>
<input type="number" name="num" class="form-control" value="<?php echo $numero; ?>" required min="0"/>
</div>
<div class="form-group">
<label>Piso: <label>
<input type="text" name="piso" class="form-control" value="<?php echo $piso; ?>" />
</div>
<div class="form-group">
<label>Codigo Postal: <label>
<input type="text" name="cp" class="form-control" value="<?php echo $codigoPostal; ?>" required />
</div>
<div class="form-group">
<label>Pais: <label>
<?php desplegable_pais(-1);?>
</div>
<div class="form-group">
<label>Poblacion: <label>
<?php echo $nombrePob." - ".$comunidad." - ".$pais; ?>
<!-- FALTA SELECT DEPENDIENTE-->
</div>
<input class="btn btn-success" type="submit" id="enviar" value="Modificar"/>
</div>
<?php } ?>
</form>
</div>
</div>
</div>
</div>
</body>
<script src="js/jquery-1.12.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/scriptLogin.js"></script>
</html>
elseif($action == "updateCenterDir"){
$ide = $_POST['ide'];
$via = $_POST['via'];
$nombre = $_POST['nombre'];
$numero = $_POST['num'];
$piso = $_POST['piso'];
$cp = $_POST['cp'];
$poblacion = $_POST['poblacion'];
$conexion = conectar();
$sql = "UPDATE DIRECCION SET via='".$via."', nombre='".$nombre."', numero=".$numero.", piso='".$piso."', codigoPostal='".$cp."', poblacion='".$poblacion."' WHERE idInstalacion=".$ide;
if($resultado = $conexion -> query($sql)){
header("Location:mod_infoDir.php?miss=1");
desconectar($conexion);
}else{
header("Location:mod_infoDir.php?miss=2");
desconectar($conexion);
}
}
You should generate the form fields from inside the while loop, and you do that but not the right way.
Right now, your while loop is closed before the form.
if($resultado = $conexion -> query($sql)){
$direcciones = mysqli_num_rows($resultado);
while($fila = mysqli_fetch_array($resultado)){
$ide = $fila[0];
$via = $fila[1];
$nombre = $fila[2];
$numero = $fila[3];
$piso = $fila[4];
$poblacion = $fila[6];
$sql = "SELECT * FROM POBLACION WHERE idPoblacion='" . $poblacion . "'";
if($resultado = $conexion -> query($sql)){
if($fila = mysqli_fetch_array($resultado)){
$codigoPostal = $fila[1];
$nombrePob = $fila[2];
$comunidad = $fila[3];
$pais = $fila[5];
}
}
?>
Generate divs here...
<?php
} // close while($fila = mysqli_fetch_array($resultado))
} // close if($resultado = $conexion -> query($sql))
?>
Move the last disconnect after the divs that generate the form.
I couldn't find an answer to this question elsewhere, I was hoping someone here might know. I've spent 9 hours straight trying to get this to work, I've been searching non-stop.
I have three PHP files. The third file contains my PHP functions to check for existing users and add users to the database
user.inc.php
<?php
//checks if given username exists in database
function user_exists($user){
$user = mysqli_real_escape_string($user);
$sql= "SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'";
$result = mysqli_query($con,$sql);
if ($result == 1){
return true;
}
else {
return false;
}
}
function email_exists($email){
$user = mysqli_real_escape_string($email);
$sql="SELECT COUNT(`user_id`) FROM `users` WHERE `user_email` = '{$email}'";
$result = mysqli_query($con,$sql);
// $row = mysqli_fetch_assoc($total);
if ($result == 1){
return true;
}
else {
return false;
}
}
//checks if given username/password is valid
function valid_credentials($user,$pass){
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$sql= "SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'AND `user_password` ='{$pass}'";
$result = mysqli_query($con,$sql);
if ($result == 1){
return true;
}
else {
return false;
}
}
//adds a user to the database
function add_user($user,$pass,$email){
mysqli_query($con,"INSERT INTO`users` (`user_name`,`user_password`,`user_email`) VALUES ('a','b','c')");
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($_REQUEST[$pass]);
mysqli_query($con,"INSERT INTO`users` (`user_name`,`user_password`,`user_email`) VALUES ('{$user}','{$pass}','{email}')");
}
?>
The second PHP file starts the connection to the database and includes the previous file at the bottom.
init.inc.php
<?php
session_start();
$exceptions = array('registerPage','login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if (in_array($page, $exceptions)=== false){
if (isset($_SESSION['username'])=== false ){
header('Location: login.php');
die();
}
}
$con = mysqli_connect('127.0.0.1','root','','yingyujiaocheng');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO `users` (`user_name`,`user_password`) VALUES ('user','pass')");
$path = dirname(__FILE__);
include("{$path}/inc/user.inc.php");
?>
The third PHP file includes the second file at the top and also has HTML and forms. When the form on the 3rd page is filled out and submitted, it sends the information to the top of the 3rd page to the PHP script. This is processed for errors which calls functions from the first files. The database works, I have done MYSQLI commands from every place, the only thing not working is the call from the 3rd PHP file to the first PHP file. The functions user_exists, email_exists and add_user to not call correctly.
Here is the third file:
registerPage.php
<?php error_reporting(E_ALL);
include('core/init.inc.php');
$errors = array();
if(isset($_POST['username'],$_POST['password'],$_POST['email'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (empty($username)){
$errors[] = 'The username cannot be empty.';
}
if (empty($password)){
$errors[] = 'The password cannot be empty.';
}
if (empty($email)){
$errors[] = 'The email field cannot be empty.';
}
if (user_exists($username)){
$errors[] = 'The username is already taken';
}
if (email_exists($email)){
$errors[] = 'The email already taken';
}
if (empty($errors)){
add_user($username,$password,$email);
//$_SESSION['username'] = htmlentities($username);
//header('Location: protected.php');
// die();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="ext/Styles/styleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="header" align="centre">
<img src="ext/Images/Logo.png" width="150" height="80" style="float:left;" />
<h2 class="headerFontClickedSmall" style="float: right; margin-top:36px; margin-right: 60px"> </h2>
<h2 class="headerFontUnclickedSmall" style="float: right; margin-top:36px; margin-right: 10px"> / </h2>
<h2 class="headerFontUnclickedSmall" style="float: right; margin-top:36px; margin-right: 10px"> </h2>
<h2 class="cornerBox1" style="float: right; margin-top:20px; margin-right: 50px"> </h2>
</div>
<div class="content">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<?php echo "Username is :" . $username . "<br>";
echo "Password is :" . $password;
?>
<br />
<h1 class="contentHeader" style=""> </h1>
<div>
<?php
if (empty($errors) === false){
?>
<ul>
<?php
foreach ($errors as $error){
echo "<li>{$error}</li>";
}
?>
</ul>
<?php
}
?>
</div>
<form action="registerPage.php" method="POST">
<h1 class="contentRegisterText" style=""> : <input class="inputbox" style="margin-left:30px" type="text"
name = "username" id="username"/> </h1>
<br />
<h1 class="contentRegisterText" style=""> : <input class="inputbox" style="margin-left:30px" type="text"
name = "email" id="email"/> </h1>
<br />
<h1 class="contentRegisterText" style="">: <input class="inputbox" style="margin-left:30px" type="password"
name = "password" id="password"/> </h1>
<br /><br /><br /><br /><br /><br />
<input style="margin-left:30px" type="submit" value = "" id="Register"/> </form>
</div>
<div class="footer" align="center" >
<div class="floating-box" style="margin-top:40px" >
<dl>
<dt><h1 class="footerTitle">社交媒体</h1></dt>
<br />
<dd><a href="http://www.huya.com/lucio">
<img src="ext/Images/HuyaLogo.png" alt=" " width="42" height="42" outline="none">
</a>
<img src="ext/Images/weixinLogo.png" width="40" height="40" style="margin-left:3;"/><img src="ext/Images/logo-qq.png" width="40" height="40" /></dd>
</dl>
</div>
<div class="floatingboxFooter1" style="margin-top:40px">
<dl>
<dt><h1 class="footerTitle"></h1> </dt>
<br />
<dd><h1 class="footerSmall">:</h1></dd>
<dd><h1 class="footerSmall">Weixin: </h1></dd>
<dd><h1 class="footerSmall">QQ: </h1></dd>
</dl>
</div>
<div class="floating-box" style="margin-top:64px">
<dl>
<br />
<dd><h1 class="footerSmall">bangzhu#yingyujiaocheng.com</h1></dd>
<dd><h1 class="footerSmall">yingyujiaocheng</h1></dd>
<dd><h1 class="footerSmall">yingyujiaocheng</h1></dd>
</dl>
</div>
<div class="floatingboxFooter1" style="margin-top:40px">
<dl>
<dt><h1 class="footerTitle"></h1> </dt>
<br />
<dd><h1 class="footerSmall"></h1></dd>
<dd><h1 class="footerSmall"></h1></dd>
<dd><h1 class="footerSmall"></h1></dd>
</dl>
</div>
</body>
</html>
Thank you for looking, any help is appreciated,
Cheers
Lucio
Try to debug the $path variable, I think the problem is in the path you included in this line.
include("{$path}/inc/user.inc.php");
Or try to insert global $con on top of every function inside user.inc.php like so:
function user_exists($user) {
global $con;
// rest of the code...
}
I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];