I have a MYSQL table with edit link and delete button on each row. The edit link goes to edit_movie.php which has a form. My problem is that the form is not showing any data to be updated/edited. How do I fetch the id from the row clicked on or what function to write to pick it up. The form is just blank, no fields are filled out.
Could someone help out I´d be very happy! Been sitting with this problem for 3 days now and just can´t get it to work. I'm a PHP beginner...
I know I'm using mysql functions which are outdated and I need to lookover SQL injection which I will once I get this working.
Table info:
Table 1 name: Movies
Fields: id (primary key, AI), title, release_year, genre_id, director
Table 2 name: Categories
Fields: genre_id (primary key, AI), genre
They have a foreign relation between genre_id.
Here is the code in index.php file
<?php
require('movie.inc.php');
if ( isset($_GET['delete']) && isset($_GET['id']) ){
if ( delete_movie_by_id($_GET['id']) ){ //it's 100% safe
die('Movie has been removed. Refresh the page now'); // or the like
} else {
echo 'Sorry movie could not be deleted'; // could not - handle here
}
}
include 'add_movie.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<table>
<tr>
<th>Title</th>
<th>Release year</th>
<th>Genre</th><th>Director</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php foreach (get_all_movies() as $index => $row) : ?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['release_year']; ?></td>
<td><?php echo $row['genre'];?></td>
<td><?php echo $row['director'];?></td>
<td><a href='<?php printf('edit_movie.php?edit=%s', $row['id']);?>'>Edit</a></td>
<td>
<form action="index.php" method="GET">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="<?php echo $row['id'];?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
Here is the edit_movie.php code:
<?php
require 'connect.inc.php';
require_once('movie.inc.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<h1>Edit movie</h1>
<div id="form_column">
<form action="edit_movie.php" method="post">
<input type="hidden" name="id" value="<?php if (isset($row["id"])) ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php if (isset($row["title"])) { echo $row["title"];} ?>" /> <br>
Release Year:<br> <input type="text" name="release_year" value="<?php if (isset($row["release_year"])) { echo $row["release_year"];} ?>" /> <br>
Director:<br> <input type="text" name="director" value="<?php if (isset($row["director"])) { echo $row["director"];} ?>" /> <br><br>
Select genre:
<br>
<br> <input type="radio" name="genre_id" value="1" checked />Action<br>
<br> <input type="radio" name="genre_id" value="2" />Comedy<br>
<br> <input type="radio" name="genre_id" value="3" />Drama<br>
<br> <input type="radio" name="genre_id" value="4" />Horror<br>
<br> <input type="radio" name="genre_id" value="5" />Romance<br>
<br> <input type="radio" name="genre_id" value="6" />Thriller<br><br>
<input type="submit" value="Update movie" />
</form>
</div>
</body>
</html>
And here is the movie.inc.php file
<?php
require_once('connect.inc.php');
function get_all_movies(){
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
$return = array();
while ($row = mysql_fetch_assoc($result)){
$return[] = array('director' => $row['director'], 'genre' => $row['genre'], 'release_year' => $row['release_year'], 'title' => $row['title'], 'id' => $row['id']);
}
return $return;
}
}
function delete_movie_by_id($id){
return mysql_unbuffered_query(sprintf("DELETE FROM `movies` WHERE id='%s' LIMIT 1", mysql_real_escape_string($id)));
}
if ( isset($_POST['delete'], $_POST['id']) ){
delete_movie_by_id($_POST['id']);
}
?>
In edit_movie.php it doesn't look like you're actually getting the movie passed view the form. You need something like this in your movie.inc.php:
function get_movie_to_edit($id) {
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id WHERE id = $id";
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
while ($row = mysql_fetch_assoc($result)){
$return = array('director' => $row['director'], 'genre' => $row['genre'], 'release_year' => $row['release_year'], 'title' => $row['title'], 'id' => $row['id']);
}
return $return;
}
}
And then in edit_movie.php you need to call this function. Something like...
if(isset($_GET['edit'])) {
$movie = get_movie_to_edit($_GET['edit']);
}
Of course, as you mentioned, you need to clean up a lot of the code to prevent against injection and check for a scenario where, say, you get to edit_movie.php and the ID ro edit doesn't exist, but this is the basic gist.
You would also then edit the values in the form in edit_movie.php to reflect the new array like:
<form action="edit_movie.php" method="post">
<input type="hidden" name="id" value="<?php echo $movie['id']; ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php echo $movie['title']; ?>" /> <br>
.... the rest of your form inputs
</form>
Updated
For the genre radio buttons...
<input type="radio" name="genre_id" value="1"<?php if($movie['genre'] == 1) { echo ' checked'; } ?> />Action<br>
<input type="radio" name="genre_id" value="2"<?php if($movie['genre'] == 2) { echo ' checked'; } ?> />Comedy<br>
.... and so on
Related
enter image description hereI'm new to PHP so please don't judge :D
I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?
$sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = $connection-> query($sql);
echo '<div style="text-align:center; font-weight: bold;">';
for ($page=1; $page<=$num_of_pages; $page++){
echo '' . $page . ' ';
}
echo '<div><br>';
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$Name = $row['Name'];
$Area = $row['Area'];
$Population = $row["Population"];
$Phone_code = $row["Phone_code"];
echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
. $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
}
print_r($row);
}
else{
echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
}
$connection-> close();
?>
</table>
<br>
<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
<form action="edit_country.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
<p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
<p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
There are two strategies that can be used for this problem: all php or using JavaScript.
PHP Only
This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.
<?php
// always start with php stuff and don't issue any html until you're done
// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
// this decouples the value from user input. It can only be 'Asc' or 'Desc'
$sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );
// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial
// $pdo is assumed to be the pdo object
// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {
// delete from countries where id = ?
//redirect back to self (Post, Redirect, Get pattern).
// Always do this when done working with POST submissions!
header('Location: /countries.php');
exit;
}
// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {
// update countries set ...
// redirect back to self
header('Location: /countries.php');
exit;
}
// deal with request for row to edit, use GET for info requests
if(array_key_exists('id', $_GET) {
$rowToEdit = $pdo->prepare("select * from countries where id = ?");
$rowToEdit->execute([$id]);
// fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);
// got all our data, dealt with user input, now we can present the view
?>
<html>
<head>
</head>
<body>
<h1>Countries</h1>
Sort Asc
Sort Desc
<table>
<tr>
<th>Name</th>
<th>Area</th>
<th>Population</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
<?php foreach( $country as $row): ?>
<tr>
<td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
<td><?=$row["Area"]?></td>
<td><?=$row["Population"]?></td>
<td><?=$row["Phone_code"]?></td>
<td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
<td>
<form method="post">
<input type="hidden" name="id" value="<?=$row['id']?>" />
<button id='delete-button'>Delete</button>
</form>
</td>
</tr>
</table>
<?php if($rowToEdit): ?>
<div style="text-align:center">
<form action="countries.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
<input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
<p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
<p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
<p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
<?php endif; ?>
</body>
</html>
I have multiple checkbox in my form and the person need to input the quantity of the types of item that is selected. Now, my problem is that I can't get the data to be inserted into database.
This is my add_record.php code:
<?php
include("connect.php");
include("header.php");
$sql_student = "SELECT * FROM student";
$result_student = mysql_query($sql_student);
?>
<form method="post" id="add_form" action="add_record.php">
<label>Name</label>
<input placeholder="Enter Student Name" type="text" name="name" id="name" class="form-control" />
<br />
<input placeholder="Enter Student ID" type="text" name="stud_id" id="stud_id" class="form-control" />
<br />
<?php
$sql_baggage = "SELECT * FROM baggage";
$result_baggage = mysql_query($sql_baggage);
?>
<label>Bag Types</label></br>
<table style="border:none;">
<?php while($row_bag = mysql_fetch_array($result_baggage))
{
$baggage_id = $row_bag['baggage_id'];
?>
<tr>
<td><?php echo $row_bag['baggage_id'];?>
<td><?php echo $row_bag['baggage_type'];?></td>
<td><input type="checkbox" name="tick[]" value="<?php echo $baggage_id;?>"/></td>
<td><input type="text" size="2" name="txt[<?php echo $baggage_id;?>]" placeholder=" "></td>
<?php
?></td></tr>
</table>
<br />
<input type="submit" name="submit" id="submit" value="Add Record" class="btn btn-success btn-secondary pull-right" />
</form>
<?php
if(isset($_POST['submit']))
{
$name = $_POST["name"];
$stud_id = $_POST["stud_id"];
$stu_query = "INSERT INTO student(student_id,student_name) VALUES ('$stud_id','$name')";
if(mysql_query($stu_query))
{
if(!empty($_POST['tick']))
{
foreach($_POST['tick'] as $selected)
{
$qty = $_POST['txt'][$selected];
$inv_query = "INSERT INTO inventory (invstu_id,invbag_id,invbag_quantity) VALUES
('$stud_id','$selected', '$qty')";
if(mysql_query($inv_query))
{
echo'<script>alert("A record has been inserted!")</script>';
}
else
{
echo "Database error";
}
}
}
else
{
echo'<script>alert("A record has been inserted!")</script>';
}
}
}
?>
</body>
</html>
I know that the data is passed through foreach function since I get the echo of database error two times when I tick two of the checkbox. However, the value is not inserted into the database.
Finally solve the issue by echoing the mysql_error(), there is nothing wrong with the code. Just a bit problem at the database. Thanks!!
I'm trying to figure out how to use the text box and radio buttons to search for items in the database. Here's my code so far. I'm a php beginner. Also I'm kinda confused btw pdo and mysqli. I'm really stuck. Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>northwind database</title>
</head>
<body>
<?php
//connect databse
$dsn = 'mysql:host=localhost;dbname=northwind';
$username ='sa' ;//'mgs_user';
$password = '123';//'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo'<p>You are connected</p>';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
require_once ('index.php');
}
?>
<?php
//PDO:: query
/*function getFruit($conn) {
$sql = 'SELECT id, first_name, last_name FROM customers ORDER BY first_name';
foreach ($conn->query($sql) as $row) {
print $row['id'] . "\t";
print $row['first_name'] . "\t";
print $row['last_name'] . "\n";
}
}*/
$query="SELECT id,Company, first_name, last_name FROM customers";
$display = $db->prepare($query);
$display->execute();
$customer = $display->fetchAll();
$display->closeCursor();
?>
<h1> Customer List </h1>
<p>Search</p>
<form name="searchDatabase" method="post" action="Index,php">
<input name="search" type="text" size="40" maxlength="50" /><br />
<input name="RadioId" type="radio" value="Id" />ID<br />
<input name="RadioId" type="radio" value="Company" />Company<br />
<input name="RadioId" type="radio" value="FName" />First Name<br />
<input name="RadioId" type="radio" value="LName" />Last Name<br />
<input name="RadioId" type="radio" value="Title" />Title<br />
<input type="submit" name="Submit" size="10" value="Search" />
</form>
<br /><br />
<table>
<tr>
<th>ID</th>
<th>Company</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<?php foreach ($customer as $cus) :?>
<tr>
<td><?php echo $cus['id']; ?></td>
<td><?php echo $cus['Company']; ?></td>
<td><?php echo $cus['first_name']; ?></td>
<td><?php echo $cus['last_name']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
I have a quiz which shows 1 question per page. If the user clicks next question without selecting a multiple choice answer, I'm trying to get validation to appear so that they can't advance unless they select an answer. When the user currently presses next question the error: 'Notice: Undefined index: answer' appears
any help?
quiz.php:
if(isset($_POST['checkQuiz'])) {
$a=$_POST['a'];
$quiz_id=$_SESSION['quiz_id'];
$index=$_SESSION['index'];
$resultQuery = mysqli_query($con,"SELECT `correctValue` FROM quiz_questions WHERE quiz_id = '$quiz_id' LIMIT 1 OFFSET $index");
$cor=0;
$incorrect=0;
while ($correct = mysqli_fetch_array($resultQuery)){
if ($_POST['answer'] == $correct[0]) {
$_SESSION['rightAnswers']+=1;
}
if ($_POST['answer'] != $correct[0]) {
$_SESSION['wrongAnswers']+=1;
}
}
}
<form method="post" action="" class="form complete">
<table>
<td>
<td width = "50" id="question"><?php echo $result['question'] . "<br>"; ?></td>
</td>
<tr height = "10"></tr>
<td id= "number" width = "20" class="number"><?php echo $questionNumber ?>)</td>
<td id = "possible_answers" height = "100"width = "700">
<input type="radio" name="answer" onClick="changeColour('a')" value="<?php echo $result['answerA'] ?>"> <?php echo $result['answerA']; ?> <br>
<input type="radio" name="answer" onClick="changeColour('b')" value="<?php echo $result['answerB'] ?>"> <?php echo $result['answerB']; ?> <br>
<input type="radio" name="answer" onClick="changeColour('c')" value="<?php echo $result['answerC'] ?>"> <?php echo $result['answerC']; ?> <br>
<input type="radio" name="answer" onClick="changeColour('d')" value="<?php echo $result['answerD'] ?>"> <?php echo $result['answerD']; ?> <br><br>
</table>
<?php
$_SESSION['questionNumber']=$questionNumber;
}
$a=$a+1;
?>
<input type="submit" name="exitQuiz" value="Exit Quiz" id="button1">
<?php
if ($questionNumber<$_SESSION['numberOfQuestions']) {
?>
<input type="submit" name="checkQuiz" value="Next Question" id="button1">
<input type="hidden" value="<?php echo $a ?>" name="a">
<?php
}
?>
<?php
if ($questionNumber==$_SESSION['numberOfQuestions']) {
?>
<input type="submit" name="checkResult" value="Quiz Result" id="button1">
<input type="hidden" value="<?php echo $a ?>" name="a">
<?php
} ?>
You need to check that $_POST['answer'] is set, like this:
while ($correct = mysqli_fetch_array($resultQuery)){
if (!isset($_POST['answer']) || $_POST['answer'] != $correct[0]) {
$_SESSION['wrongAnswers']+=1;
} elseif ($_POST['answer'] == $correct[0]) {
$_SESSION['rightAnswers']+=1;
}
}
I'm struggling now for a few days to get the value of a checkbox in my code.
Basically I have an admin-page where the customer can select and deselect images that will put online.
You can select and deselect images that will be shown on the homepage, and separate on the gallery-page. Both checked is also possible.
I have another checkbox that can be selected to remove the image from the list(image_deleted).
There is still a database entry and the images are still on file-system but later on I'll create a cleanup-job.
Here is my code:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
require('../../lib/dbconnection.php');
require("../../lib/checklogin.php");
require("includes/upload.inc.php");
$query = 'SELECT * FROM gallery where image_deleted != 1 order by id desc';
$result=$conn->query($query);
$count=$result->num_rows;
?>
<!DOCTYPE html>
<html>
<head>
<title>Classic Nails - CMS</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="ClassicNails">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/screen.css">
<link rel="stylesheet" href="../css/libs/magnific-popup.css">
<script src="../js/libs/min/jquery-min.js" type="text/javascript"></script>
<script src="../js/min/custom-min.js" type="text/javascript"></script>
<script src="js/jquery.magnific-popup.js"></script>
<script>
$(document).ready(function() {
$('.image-link').magnificPopup({
type:'image',
gallery:{
enabled:true
}
});
});
</script>
</head>
<body>
<?php include('includes/header.inc.php'); ?>
<?php include('includes/nav.inc.php'); ?>
<div class="wrapper">
<article class="content">
<h1>Foto gallery</h1>
<?php
if (isset($uploadResult)) {
echo "<p><strong>$uploadResult</strong></p>";
}
?>
<form action="" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">Upload image:</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<input type="file" name="images" id="imagesd" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<div id="maincontent">
<h2>Foto informatie</h2>
<form name="FotoInformatie" id="fotoInformatie" method="post" action="">
<table>
<tr>
<td align="center"><strong>Foto<strong></td>
<td align="center"><strong>Titel</strong></td>
<td align="center"><strong>Beschrijving</strong></td>
<td align="center"><strong>Homepage</strong></td>
</tr>
<?php
while ($rows=$result->fetch_assoc()) {
?>
<tr>
<td class="hide" align="center"><?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?></td>
<td><img src="../img/thumbs/<?php echo $rows['filename']; ?>"></td>
<td align="center"><input name="title[]" type="text" id="title" value="<?php echo $rows['title']; ?>"></td>
<td align="center"><input name="caption[]" type="text" id="caption" value="<?php echo $rows['caption']; ?>"></td>
<td><input type="checkbox" name="checkboxHome[]" id="checkBoxHome" value="<?php echo ($rows['home'] == 1) ? 'checked="checked"' : ''; ?>"/></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center">
<input type="submit" name="submit" value="Submit">
</tr>
</table>
</form>
</div>
</article> <!-- end of content -->
</div> <!-- end of container -->
<?php include('includes/footer.inc.php'); ?>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$caption = $_POST['caption'];
if ($_POST['checkboxHome'] == "") {
$checkboxHome[] = '0';
} else {
$checkboxHome[] = '1';
}
for($i=0;$i<$count;$i++){
$result1=mysqli_query($conn, "UPDATE gallery SET title='$title[$i]', caption='$caption[$i]', home='$checkboxHome[$i]' WHERE id='$id[$i]'");
header("location:/admin/foto-admin.php");
}
}
?>
The checkbox only works on the first row in my DB. When I select another record, only the first record in my db will be updated.
Another issue is that my checkbox won't be checked so I don't know based on my screen when a image is online or not. in the database I see a 1 of a 0.
I know that sql-injection is possible and I have to prepare the statements, but that is the next step when I get this checkbox-issue working.
Hope someone can help me with my code. It's giving me a headache.
Check these
Attribute name="id[]" for id field is not given. And it should get inside
if(isset($_POST['submit'])) {
$id = $_POST['id'];
}
Incorrect spelling in getting Post value
change
$checkboxHome = $_POST['checkboxHome'];
$checkboxFotoboek= $_POST['checkboxFotoboek'];
$checkboxDelete = $_POST['image_deleted'];
to
$checkboxHome = $_POST['checkBoxHome'];
$checkboxFotoboek= $_POST['checkBoxFotoboek'];
$checkboxDelete = $_POST['checkboxDelete'];
You are trying to get wrong value.
Your check-box name is checkBoxHome and you are trying to get $_POST['checkboxHome'] instead of $_POST['checkBoxHome'] .
Try $_POST['checkBoxHome'] and print it as print_r('checkBoxHome')
Same mistake in checkBoxFotoboek check-box.
try this
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$caption = $_POST['caption'];
$checkboxHome = $_POST['checkBoxHome'];
$checkboxFotoboek= $_POST['checkBoxFotoboek'];
$checkboxDelete = $_POST['checkboxDelete'];
for($i=0;$i<$count;$i++){
$result1=mysqli_query($conn, "UPDATE gallery SET title='$title[$i]', caption='$caption[$i]', home='$checkboxHome[$i]', fotoboek='$checkboxFotoboek[$i]', image_deleted='$checkboxDelete[$i]' WHERE id='$id[$i]'");
header("location:/admin/foto-admin.php");
}
}
?>