The form is supposed to delete a customer row from the customer table by entering customer ID, but it is not doing what it is supposed to, I dont know why! When I executed the PHP file I dont get any errors.
I know it should work because I used the same code to delete information from the employee table and it worked fine.
Delete Customer Form
<!DOCTYPE html>
<head>
<?php include 'project_header.php'; ?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form action="customer_delete.php" method="post">
<h2> Delete a Customer</h2>
<p>Please Enter Customer Information:</p>
Customer ID: <input type="text" ID="Customer_ID"/><br>
<input type="submit" value= "Delete"/><input type="reset"/>
</form>
</body>
<?php include 'project_footer.php'; ?>
</html>
Delete Customer PHP
<!DOCTYPE html>
<html>
<?php include 'project_header.php'; ?>
<body>
<?php
include_once 'db.php';
include_once 'display.php';
#form data
$Customer_ID=$_POST['Customer_ID'];
$sql = "delete from CUSTOMERS where Customer_ID = :Customer_ID;";
$stmt = $conn->prepare($sql);
# data stored in an associative array
$data = array( 'Customer_ID' => $Customer_ID);
if($stmt->execute($data)){
$rows_affected = $stmt->rowCount();
echo "<h2>".$rows_affected." row deleted sucessfully!</h2>";
display("select Customer_ID as Customer ID FROM CUSTOMERS;");
}
else
{
echo "\nPDOStatement::errorInfo():\n";
print_r($stmt->errorInfo());
}
$stmt = null;
$conn = null;
?>
</body>
<?php include 'project_footer.php'; ?>
</html>
It seems that there is no name attribute on your text box. This is how PHP gets the POST information, so without it being set, you can't access what the user inputted. Simply change the attribute from ID to name(or just add the name attribute if id is needed) and that should fix the issue.
Customer ID: <input type="text" ID="Customer_ID"/>
In this line you need to add the "name" attribute, and that should fix the issue.
What you should do is:
Customer ID: <input type="text" ID="Customer_ID" name="Customer_ID"/>
Greetings!
Related
For the past two hours, I have been trying to create a simple insertion form that connects to a SQLite. For some reason, the insertion of a new record won't work. I get no error message when I run my app using php -S localhost:1234. My form is just emptied out without any insertion after a click on the Submit button.
My database is named database.db, the table is named students_tb, and the columns in the table are id, sname and score.
Here is my code, which is based on https://www.youtube.com/watch?v=cyl0Oj3rmmg&list=PLU70qqWW4frENsWYAm-tAKp2ZJQ_dt3WR&index=8. I checked and rechecked the 3-minute-long tutorial, but wasn't successful at tracking down my bug. I guess this must be a silly mistake, but I really can't find it.
<!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>Add Student</title>
<style>
label, input {
display: block;
}
</style>
</head>
<body>
<h1>Add student to database</h1>
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required>
<label for="score">Score</label>
<input type="number" name="score" required>
<button type="submit">Submit</button>
</form>
<?php
} else {
try {
$db = new PDO("sqlite:database.db");
$sql = "INSERT INTO students_tb (sname, score) VALUES (:sname, :score)";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been added to the database.";
} else {
echo "The student has NOT been added to the database.";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
</body>
</html>
It has been a while since I worked in PHP, but I think the problem might be in the HTML code of the form. You have:
<button type="submit">Submit</button>
And your PHP code is checking for a value of the variable named submit, but this field does not have a name, only a type. Should it be:
<button type="submit" name="submit">Submit</button>
I want to Create an ItemList and simply display it. For this, I have created an array and a form with add item "text field" and "submit" button.
The problem is when I add a new value by clicking on the "submit" button, the page gets reloaded and previously added values are lost. I want previously added values to persist, without storing these data into the database.
Please help me I am a beginner in this field.
Code :
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP ItemList</title>
</head>
<body>
<div class="container">
<?php
$itemList = array();
if ( $_SERVER["REQUEST_METHOD"] == "POST") {
array_push( $itemList, $_POST["Item"] );
print_r( $itemList );
}
?>
<h3>Add : </h3>
<form method="POST" action = "index.php">
<p>Item : <input type="text" name="Item"></p>
<input type="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
My blog was posting originally, however, as you work on things, things break. Now I can't for the life of me figure out why nothing is happening! The categories post to the database just fine, but my posts refuse to. Heres what I have
<?php
include_once('header.php');
if(isset($_POST['title'], $_POST['contents'], $_POST['category'])){
$errors = array();
if(!empty(trim($_POST['title']))){
$title = trim($_POST['title']);
}else{
$errors[] = 'Please enter title';
}
if(!empty(trim($_POST['contents']))){
$contents = trim($_POST['contents']);
}else{
$errors[] = 'You need to supply the content';
}
if(!category_id_exists($_POST['category'])){
$errors[] = 'That category does not exist.';
}
if(strlen(trim($_POST['title']))>255){
$errors[] = 'The title cannot be longer than 255 characters.';
}
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
label { display: block;}
</style>
<title>Add a Post</title>
</head>
<body>
<h1> Add a Post </h1>
<?php
if(isset($errors) && !empty($errors)){
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<form action="" method="post">
<div>
<label for="title"> Title </label>
<input type="text" name="title" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>">
</div>
<div>
<label for="contents"> Contents </label>
<textarea name="contents" rows="15" cols="50"><?php if(isset($_POST['contents'])) echo $_POST['contents']; ?></textarea>
</div>
<div>
<label for="category"> Category </label>
<select name="category">
<?php
foreach(get_categories() as $category){
?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?> </option>
<?php
}
?>
</select>
</div>
<div>
<input type="submit" value="Add Post">
</div>
</form>
</body>
</html>
Inside the header.php file, I call an init.php connect to db file which also in itself, include_once all the functions for my blog (blog.php). The function that specifically is necessary is as follows...
function add_post($title, $contents, $category){
global $mysql_connect;
$title = mysqli_real_escape_string($mysql_connect, $title);
$contents = mysqli_real_escape_string($mysql_connect, $contents);
$category = (int)$category;
$result = mysqli_query($mysql_connect, "INSERT INTO posts SET cat_id = '$category', title = '$title', contents = '$contents', date_posted = NOW()");
}
I figured a fresh set of eyes could be really valuable for me right now. When I click add post, it brings me to a page titled http://localhost/blog/index.php?id=0. Therefore it's not only not registering to the database, but it's not using the categories either.
I hope I explained this okay! I've been at this for a week now.
Edit: I ran error checks and nothing posts, so I am not sure what's going on!
Edit2: Selecting categories I add, also work and list the way I want them to. Its just something happening when I go to click add post, nothing occurs. I'm assuming its in this area
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
As with any problem, it's always a needle in a haystack! I ran code through MYSQL workbench, and found out it was my setting to a foreign key that didn't need a relationship. It's all fixed now!
SQL Error Screenshot
I think the problem is with your database table posts.
One Case is:
You need to have an AUTO_INCREMENT field (id for example) so that the function mysqli_insert_id works perfectly. And in your case the solution would be to make the id column an AUTO_INCREMENT field.
Here is a quote:
The mysqli_insert_id() function returns the ID generated by a query on
a table with a column having the AUTO_INCREMENT attribute. If the last
query wasn't an INSERT or UPDATE statement or if the modified table
does not have a column with the AUTO_INCREMENT attribute, this
function will return zero.
I really don't know how to describes this, but here goes. I'm trying to make a Login for an online multiplayer game (cluedo to be exact) that is written using mainly the LAMP stack (php,js,etc), and creating a session when someone logs in/registers works for me and all and I even save it to a sql database, but it seems that as soon as a next user Logs in/registers the session id to the previous user is overridden to the new ones details. In other words they both now have the same session for some reason.
My Game LogIn basically:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Game Setup</title>
</head>
<body>
<header>
<h1>Game Setup</h1>
</header>
//My form for user details and character select
<form name="Registration" id=Form1 action="Lobby.php" method="POST">
<fieldset>
<legend>Player information:</legend>
<label for="Pid">Player Name(required): </label><br>
<input autofocus type="text" id="Pid" name="Pid" placeholder="Player ID" required><br>
<label for="Avatar">Character(required):</label><br>
<select name="Avatar">
<option value="Miss White">Miss White</option>
<option value="Col Mustard">Col Mustard</option>
<option value="Miss Scarlet">Miss Scarlet</option>
<option value="Mr Green">Mr Green</option>
<option value="Madame Plum">Madame Plum</option>
<option value="Benjamin Blue">Benjamin Blue</option>
</select><br><br>
<input type="submit" value="Register">
</fieldset>
</form>
</body>
and the lobby (where I wait for someone to press game start or for more people to register)
<?php
session_start() ;
session_regenerate_id();
$_SESSION["UserName"]=$_POST['Pid'];
$_SESSION["Avatar"]=$_POST['Avatar'];
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<?php
$PlayerID = mysqli_real_escape_string($conn, $_POST['Pid']);
$PlayerChar = mysqli_real_escape_string($conn, $_POST['Avatar']);
$SesID = session_id();
$sql = "INSERT INTO users (UserName, Avatar, sessionID)
VALUES ('$PlayerID', '$PlayerChar','$SesID')";
if ($conn->query($sql) === TRUE) {
echo "Welcome $PlayerID , currently in Lobby: <br>";
$User = new Users();
$User->setUserName($_SESSION['UserName']);
$User->setAvatar( $_SESSION['Avatar']);
$User->isPlaying = false;
$_SESSION['User'] = serialize($User);
?>
<html>
<body>
<div id="Players"> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src ="Display.js"></script>
</body>
</html>
<?php
}
else {
if($conn->errno == 1062){//when a userName or Character already in use
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
$sql = "ALTER TABLE users AUTO_INCREMENT = ".$result->num_rows;
$conn->query($sql);
echo "<script type='text/javascript'>alert('ERROR :Username or Character already in use!')</script>";
echo" <script>
window.location = 'LogIn.php';
</script>";
}
}
?>
and then the Display.js runs in a loop until either 6 people connect or a user presses start. It also displays everyone currently waiting for a game by outputting the SQL database, but I don't think that code is necessary to add, but then when that's done I go to the Cluedo.php page and if I echo session_id() there on two different browsers(same machine) I get the same session_id()
<?php
session_start() ;
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Cluedo</title>
</head>
<body>
<?php
$User = unserialize($_SESSION['User']);
echo session_id();
?>
</body>
</html>
Also I'm using XAMPP and running it all locally at the moment so don't know if there's a problem there maybe?
Here's an example of my database with the saved values, the table saves unique sessions however when the session_id() is echoed at the Cluedo.php page it is always the last registered user:
UserTable
On my site when a user is logged in, they can give a 1-5 rating on a movie.
What I want to do is make it so that database knows which user gave the rating and to update there rating if they click it again rather than creating a new entry, so each user can not have more than one rating per movie.
Tables:
login - id, user, password
movies - id, movie_name, movie_year
user_movie_ratings - id, user_id, movie_id, rating
At the moment when you login, you're taken to a members page the session is checked to ensure you're logged in, and then the list of all the movies is displayed and then when you click the move name you get take to a rating page where you can give it a rating of 1-5, then you are taken back to the movie page and the avg total rating is displayed beside the move name.
The user can just keep doing this over and incorrectly changing the avg rating.
I think I know what I have to do I just dont know how to do it:
Get session user name compare to database user name
Get the id linked to that user name
Post that id with the rating
Use UNIQUE KEY and ON DUPLICATE KEY UPDATE in some way to insure that they can only post once else it gets updated
movie.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<?php
require_once 'sessionCheck.php';
require_once 'init.php';
$movie = null;
if(isset($_GET['id']))
{
$id = (int)$_GET['id'];
$movie = $con->query
("
SELECT movies.id, movies.movie_name, AVG(user_movie_ratings.rating) AS rating
FROM movies
LEFT JOIN user_movie_ratings
ON movies.id = user_movie_ratings.movie_id
WHERE movies.id = {$id}
")->fetch_object();
}
?>
<head>
<title>Movies</title>
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="login">
<?php include 'loginCheck.php';?>
</div>
</div>
<div class="content">
<?php if ($movie): ?>
<div class="movie">
Movie Name: <?php echo $movie->movie_name; ?>.
<div class="movie_rating">
Rating: <?php echo round($movie->rating); ?>/5
</div>
<div class="movie-rate">
Rate this movie:
<?php foreach(range(1, 5) as $rating): ?>
<?php echo $rating; ?>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
</div>
<div id="footer"> This is the Footer</div>
</div>
</body>
</html>
rate.php
<?php
require_once 'init.php';
if(isset($_GET['movie'], $_GET['rating'])) {
$movie = (int)$_GET['movie'];
$rating = (int)$_GET['rating'];
if(in_array($rating, array(1, 2, 3, 4, 5))) {
$exists = $con->query("SELECT id FROM movies WHERE id = {$movie}")->num_rows ? true : false;
if ($exists) {
$con->query("INSERT INTO user_movie_ratings (movie_id, rating) VALUES ({$movie}, {$rating} )");
}
}
header('Location: movie.php?id=' . $movie);
}
login
<!doctype html>
<html>
<body>
<p>Register</p>
<form action="" method="POST">
Username: <input type="text" name="user"><br />
Password: <input type="password" name="pass"><br />
<input type="submit" value="Login" name="submit" />
</form>
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass']))
{
$user=$_POST['user'];
$pass=$_POST['pass'];
require_once 'init.php';
$query=mysql_query("SELECT * FROM login WHERE username='".$user."' AND password='".$pass."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($user == $dbusername && $pass == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
/* Redirect browser */
header("Location: member.php");
}
}
else
{
echo "Invalid username or password!";
}
}
else
{
echo "All fields are required!";
}
}
?>
</body>
</html>
I'll list the steps you need to undertake in order to achieve what you want.
Store the USER_ID to the session along with their username (or any other data). Do not store username and then query every time to obtain their ID. That makes no sense
Add a unique key (user_id, movie_id) and this is the fun step - do not perform any kind of checks, just insert the data. If the user has voted for the movie, the key will be there and the insert will fail. In PHP this will be interpreted as an exception and that's what you want
Catch the exception in case of failure and notify the user they have already voted.
Use prepared statements to avoid any potential SQL injections and to speed things up (MySQL plays nicely with performance and prepared statements)
Overall, you can reduce your logic and your code if you follow these steps.