PHP MySQL Get the value of a dynamic select - php

I have a table item (id, name, content, categories id (foreign key table category)) and a category table (id, title)
name: type text
content: textarea
categories_id: select dynamics related to the category table
Inserting the item table that works very well but in the modification. I have a problem with the dynamic select to the list of categories, not pick me a choice that I chose to add a article.
How I can get the value of the select tag? <select> <option></option> </select>
<?php
include 'dbconnect.php';
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM articles WHERE id ='".$id."'");
$res = mysql_fetch_assoc($sql);
if (#$_REQUEST['do'] == "update") {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id =' $m_id' ");
if($sql)
header("Location:listArticles.php");
else
header("Location:updateArticle.php");
}
?>
<html lang="en">
<body class="nav-md">
<?php if (isset($_GET['id']) && $_GET['id'] == $id) { ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type ="text" name ="nom" value="<?php echo $res['nom'] ?>"></td>
</br>
<td>Contenu: <textarea name ="contenu"><?php echo $res['contenu'] ?></textarea></td>
</br>
<td>
Categories:
<select class="form-control" name="categories_id" value="<?php echo $res['categories_id'] ?>" >
<option></option>
</select>
</td>
<td>
<button type="submit" class="btn btn-success" name ="do" value="update">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
</table>
</form>
<?php } ?>
</body>
</html>
That is what the page currently looks like:

If I understand you correctly (and judging by the picture), you want to show the categories and select the category associated with the article.
Here's a rough, untested sketch of how you can approach. Read my comments also.
<?php
include 'dbconnect.php';
// assuming ID is integer, we'll use intval()
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
// query article matching given ID
$articleRes = mysql_query("SELECT * FROM articles WHERE id ='" . $id . "'");
$article = mysql_fetch_assoc($articleRes);
// query categories
$categoriesRes = mysql_query("SELECT * FROM categories");
// check if form has been submitted
// if you are expecting POST, use $_POST not $_REQUEST
// don't use #, it's sloppy
if (!empty($_POST['do'])) {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
// update article with given ID
// is it nom or name?
$updateRes = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id='$m_id'");
if ($updateRes) {
header("Location: listArticles.php");
} else {
header("Location: updateArticle.php");
}
// good practice to die after you redirect
die();
}
?>
<html lang="en">
<body class="nav-md">
<?php if ($article) : ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type="text" name="nom" value="<?php echo $article['nom'] ?>"></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>Contenu: <textarea name="contenu"><?php echo $article['contenu'] ?></textarea></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>
Categories:
<!-- SELECT tag does not have a VALUE attribute -->
<select class="form-control" name="categories_id">
<!-- loop through the categories and build the OPTION tag -->
<!-- for each iteration, check if the category ID matches the article's category ID -->
<!-- if so, mark the option as selected -->
<?php while ($category = mysql_fetch_assoc($categoriesRes)) : ?>
<option <?php echo $category['id'] == $article['categories_id'] ? 'selected' : '' ?>><?php echo $category['title'] ?></option>
<?php endwhile ?>
</select>
</td>
<td>
<!-- unnecessary to have VALUE attribute as this element will always be submitted -->
<button type="submit" class="btn btn-success" name="do">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $article['id'] ?>">
</table>
</form>
<?php endif ?>
</body>
</html>
Additional points:
Stop using mysql_* functions! They are deprecated for good reasons. Use mysqli_* or better PDO functions.
Your queries are prone to SQL injection.
When mixing PHP control structures (e.g. if, while, etc) with HTML, I like to use their alternative syntax (e.g. if (condition): and endif; while (condition): and endwhile; etc). It looks more readable, imo.
I am using the ternary operator which is a shorter syntax for simple if/else statements.
Add comments!

Update your update query:
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id ='$m_id' ");
For suggestion:
use mysqli_() as mysql_ are depreciated please follow the link: Why shouldn't I use mysql_* functions in PHP?
take care of sql injection
don't suppress the warning using (#)

Related

PHP PDO Crud advice

I have just started to learn PDO and have managed to do simple CRUD operations on one single table.
I am just doing a SELECT * from the table. But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID.
So my table structure is the following. I have a joke table with id and joketext and a foreign key authorId. The author table has authorId and name for the author.
Instead of doing SELECT * on the joke table, I would rather create a view with the following code:
SELECT
joke.joketext,
author.name
FROM
author
INNER JOIN joke
ON author.id = joke.authorid
But for the CRUD operations I would like to show the author.name in a dropdown instead, so the users don't erroneously put in wrong values.
This is how index.php looks like:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
$result = $dbConn->query("SELECT * FROM joke ORDER BY id DESC");
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Joke</td>
<td>AuthorId</td>
<td>Update</td>
</tr>
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>".$row['joketext']."</td>";
echo "<td>".$row['authorid']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
and my edit file looks like this:
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name=$_POST['joketext'];
$authorid=$_POST['authorid'];
// checking empty fields
if(empty($joketext) || empty($authorid)) {
if(empty($joketext)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($authorid)) {
echo "<font color='red'>Author field is empty.</font><br/>";
}
} else {
//updating the table
$sql = "UPDATE joke SET joke=:joketext, authorid=:authorid WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->bindparam(':id', $id);
$query->bindparam(':joketext', $joketext);
$query->bindparam(':authorid', $authorid);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$sql = "SELECT * FROM joke WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->execute(array(':id' => $id));
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$joketext = $row['joketext'];
$authorid = $row['authorid'];
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Joke</td>
<td><input type="text" name="joketext" value="<?php echo $joketext;?>"></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="authorid" value="<?php echo $authorid;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
Can someone show me a hint on at least the edit operations how the php code would like?
thanks
If you wish to provide a select element of available authors for the user to choose from on the edit page, rather than have them enter an ID number for an author, then you can select all the authors from the database and loop through them, building the options of your select element. A select element can show the user the name of the author, but pass the ID of the author back to the server. You can also pre-select an author to show the user the currently associated author by default and they only have to change it if it's wrong.
So first, select all the authors from the database:
$authorSql = 'SELECT * FROM author';
$authorQuery = $dbConn->prepare($authorSql);
$authorQuery->execute();
Then use that data to build a select element:
<select name="authorid">
<?php
while($author = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
if ($author['id'] == $authorid) {
//The author is currently associated to the joke, select it by default
echo "<option value=\"{$author['id']}\" selected>{$author['name']}</option>";
} else {
//The author is not currently associated to the joke
echo "<option value=\"{$author['id']}\">{$author['name']}</option>";
}
}
?>
</select>
The output might look something like this:
<select name="authorid">
<option value="1">George Carlin</option>
<option value="2" selected>Richard Pryor</option>
<option value="3">Don Rickles</option>
</select>
Whatever option the user selects, they'll see on the page what is between the <option></option> tags, but the form will pass the value of the value property to the server as the authorid parameter.
The code that generates the select element replaces the <input type="text" name="authorid" value="<?php echo $authorid;?>"> and remains within the <td></td> tags.
Hope I managed to address your actual need, let me know if I missed the intent of your question.
Note: my code isn't tested, so some adjustment may be required.
EDIT #1: Fixed incorrect variable names.

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth

PHP Delete record from database MySql

I need to delete a record, in this case a categories from my forum, from the database based on its id.
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" value="<?= ['cat_id']; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
}
?>
</td>
<?php
}
?>
i cant get a "good" way to do it... :(
EDIT: This is for a programming lesson not a real forum!!
Your HTML Input Field needs a name so it can be identified by your PHP.
Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.
Another thig you want to do is read up onj the dangers of SQL injections.
If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way.
Nontheless, try this:
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" name="hid_catid" id="hid_catid" value="<?php echo $cat_id; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
}
?>
</td>
<?php
}
?>
--> hidden field should have name and id to use
--
Thanks
Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?
<form method="post">
<input type="hidden" name="cat_id" value="<?= $cat_id ?>">
<input type="submit" name="submit" value="Remover" />
</form>
Then your query has to look like this to correctly grab the id from the post.
mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

What am I doing wrong? Edit table data in form [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a table with a edit link and a delete button on each row. Delete button is working fine but the edit link I don´t know what I´m doing wrong with!
Clicking the edit link for a specific row it leads to edit page with the form BUT the data is not filled out. There is no error message... I can see up in the URL field that it´s the correct id for the chosen movie.
What am I missing? Do I need to write any queries etc on the edit page as well? I did try and make it a require page so when clicking on the edit button the edit form pops up on the index page. But I couldn't manage to do that.
I know I'm using mysql functions which are outdated, and I have yet to add SQL protection.
The database is called moviedata and has 2 tables.
Table 1 is called: movies
Fields/columns (5): id (primary key, AI), ****title** , release_year,** ****genre_id**, **director****
Table 2 is called: categories
Fields/columns (2): genre_id (primary key, AI), genre
There is a relation (Foreign key) between genre_id (primary key, table 2) and genre_id (table 1).
index.php code
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
if (!mysql_query($query, $sql))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>' .$row["title"] . '</td>' ;
echo '<td>' .$row["release_year"] . '</td>' ;
echo '<td>' .$row["genre_id"] . '</td>' ;
echo '<td>' .$row["director"] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row["id"] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row["id"] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
?>
</body>
</html>
And here is the code on edit_movie.php page. The edit page with the form:
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
?>
<p>Edit movie</p>
<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" />
</form>
</div>
</body>
</html>
The database connection is in a separate connect.inc.php file which is required at the top of these files. The code in the connect.inc.php file you can see below:
<?php
//connect to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
//select database
mysql_select_db("moviedata");
?>
Well, your code is kinda mess, because it's not even procedural. You're making problems for yourself. Really.
There are some things you must remember when developing an application using PHP:
Never print/echo html tags.
Try to avoid this as much as possible because this makes your code unmaintainable and unreadable. Use an alternate syntax instead.
That is, PHP should be used as a template engine itself, not "generate" the ones.
Separate responsibilities. Clearly and wisely
A functions which connect to a database should not be used in a presentation (in this case - HTML). You'd create one file which is responsible for database, another one which is responsible for data manipulation(such as DELETE, CREATE, UPDATE operations) and the like.
Don't forget about SQL injection & XSS
Never trust data you get from superglobals like $_GET, $_POST, $_COOKIE and $_REQUEST. At minimum, mysql_real_escape_string() should be used for each dynamic input you are going to deal with.
Generally speaking, XSS allows to execute any JavaScript code via aforementioned superglobals as well as injecting another html code within general markup. In order to prevent this, basically htmlentities() would be great enough here.
Wrap things into a function
So instead of doing this,
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
You should re-write it like so:
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']); // it's safe & readable now
}
Learn about OOP and switch to PDO
Well, a procedural code is not the way to go when you're developing something like this. Next time you will be writing something, you'd really start using both PDO for database access and OOP.
I could go on, but it's better to stop now, and switch back to your original question.
Well, you didn't say which error exactly you get. For example, do you know if mysql_select() returns FALSE ( === failure on database selection), this won't terminate the script!? According to code you've posted, you do not "track it" in any way.
First
So, connect.inc.php should look like this:
error_reporting(E_ALL); // <-- Important!
$servername = "localhost";
$username = "root";
$password = "";
if ( ! mysql_connect($servername,$username,$password) ){
die(sprintf('Cannot connect to MySQL server because of "%s"', mysql_error()));
}
//select database
if ( ! mysql_select_db("moviedata") ){
die(sprintf('Cannot select a database, because of "%s"', mysql_error()))
}
Second
In edit_movie.php page, this code block, isn't required at all. The connection will be closed automatically when a script terminates.
So just remove this:
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
Third
In that edit_movie.php, you're clearly asking: if ( isset($row['some_column']) )..., but what is it all about? Where's the $row itself? it wasn't defined anywhere, so you won't get what you expect. Here:
<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>
Okay, that's enough.
Consider, rewriting your application like this:
File: movie.inc.php
require_once('connect.inc.php');
/**
* Fetch all movies from a table
* #return array on success, FALSE on failure
*/
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_id' => $row['genre_id'], 'release_year' => $row['release_year'], 'title' => $row['title'], 'id' => $row['id']);
}
return $return;
}
}
function delete_movie_by_id($id){
// I already wrote this, see above
}
File index.php
<?php
require('movie.inc.php');
if ( isset($_GET['delete']) && isset($_GET['id']) ){
if ( delete_movie_by_id($_POST['id']) ){ //it's 100% safe
die('Movie has been removed. Refresh the page now'); // or the like
} else {
// could not - handle here
}
}
?>
<!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_id'];?></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>
I'm tired now, hope you can get the core idea from this answer.
UPDATE
There are basic steps to make a movie "editable" :
1) You grab the data you are going to edit (from the table)
2) You send edited data back to the server (php script)
3) You validate the input
4) You run UPDATE query
That's all.
So it would be similar to this (File: edit_movie.php):
<?php
require_once('movie.inc.php');
/**
* Grabs the movie data by its id
*
* #param $id A movie id
* #return array on succes, FALSE if $id is wrong
*/
function get_movie_by_id($id){
$query = sprintf("SELECT * FROM `enter_movie_table_name_here` WHERE `id` = '%s' LIMIT 1", mysql_real_escape_string($id));
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
return $result;
}
}
function update_movie_by_id($id, array $data){
$query = sprintf("UPDATE `the_movie_table`
SET `director` ='%s',
`genre_id` = '%s',
`relase_year` ='%s',
`title` = '%s' WHERE `id` = '%s' LIMIT 1"),
mysql_real_escape_string($data['director']),
mysql_real_escape_string($data['genre_id']),
mysql_real_escape_string($data['relase_year']),
mysql_real_escape_string($data['title']),
mysql_real_escape_string($id) );
// not mysql_query() !!! but this
return mysql_unbuffered_query($query);
}
// Next thing is to get an id by query string,
// So if it was /movide_edit.php?id=1
// then id we have is 1
// So we need to handle that right now
if ( isset($_GET['id']) ){
$movie = get_movie_by_id($_GET['id']);
if ( ! $movie ){ // <- make sure that id isn't fake
die(sprintf('Invalid movie id "%s"', $_GET['id']));
}
} else {
die('Please supply an id you want to edit'); // <- this makes sence
}
// Ok, we'll reserve this block for an update
if ( !empty($_POST) ){ // This will run when user clicked on Save button
if ( update_movie_by_id($_POST['id'], array(
'director' => $_POST['director'],
'genre_id' => $_POST['genre_id'],
'relase_year' => $_POST['relase_year'],
'title' => $_POST['title']
)) ){
die('Movie has been updated');
} else {
die('Could not update a movie for some wicked reason..');
}
}
// That's all. Now it can:
//1) Fetch the data
//2) Edit accordingly
?>
<!DOCTYPE html>
<html>
<!--
This is kinda quick and dirty form
You need to fix this later
-->
<body>
<form method="POST">
<label for="title">Title</label>
<input type="text" name="title" value="<?php echo $movie['title']; " />
<!--
Add another elements this way..
-->
<button type="submit">Save</button>
</form>
</body>
</html>

Categories