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.
Related
When user inputs text in 'ctext' field and press accept, I want to fill the value=" " field with user input, i achieved this but it fills all the value fields of same name in the page, how can i achieve it for different value of different ctext input? Anyone please give me solution with example, Many thanks
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
$i=0;
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here" value="<?php $ctext = false; if(isset($_POST['ctext'])){ $ctext = $_POST['ctext']; } echo $ctext[$i]; ?>"></input>
<input type="hidden" name="id" value="<?php $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
$i++;
endwhile;
endif;
endif;
?>
I hope I understand what you want. You want to access the ctext for each individual $pen when printing the corresponding form.
You just need to name your <input> with a unique name and then access that value when printing. A possible solution is this:
<input type="text" name="ctext[<?php echo $pen['id']; ?>]" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } echo $ctext; ?>"></input>
What does it do?
name="ctext[<?php echo $pen['id']; ?>]" ensures a unique name for each $pen. For a $pen with id 1 this will result in name="ctext[1]".
if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } uses $pen['id'] to look up the corresponding value in $_POST['ctext'].
By the way, when outputting user input you should always escape it, e.g. with htmlspecialchars. This will look like this: echo htmlspecialchars($ctext); That way malicious input like "><script>alert('Hello!')</script> won't execute the javascript.
Update: as requested a solution using session to store data:
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
session_start();
if (isset($_POST['ctext'])) {
$_SESSION['ctext'][$_POST['id']] = $_POST['ctext'];
}
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_SESSION['ctext'][$pen['id']])){ $ctext = $_SESSION['ctext'][$pen['id']]; } echo htmlspecialchars($ctext); ?>"></input>
<input type="hidden" name="id" value="<?php echo $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
endwhile;
endif;
endif;
Note: I removed the now unnecessary counter $i. The session handling is mainly done before the while loop (start a session and store POST data). During output the values from the session are used. The name of the input is not an array anymore.
Change name of an input to an array.like this . When you submit the form you will get these values as an array. Give it a try
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here"></input>
I guess your code is misleading you, your form is in while loop so once any of the ctext input is filled your variable $_POST['ctext'] is set on server side and according to your code it sets all the value of ctext once accept is pressed.
You can have different names as a solution or an array indexing in input field name=“ctext[]” to avoid this.
I have a data base 'School'. It has only one table - 'Words'. There are word_id, word_name, word_description in it. I want to pull a random description and display it on a page. Then I want to input a word and see if the word has the same description as the random one that was pulled. What am I doing wrong? Here is the code -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Изпит</title>
</head>
<body>
<?php
$connection = mysqli_connect('localhost', 'root', '', 'school');
if(!$connection){
echo 'NOT OK';
exit;
}
if(isset($_POST['submit_description'])){
$q = mysqli_query($connection, ' SELECT word_description
FROM words ORDER BY rand() LIMIT 1
');
$row=mysqli_fetch_assoc($q);
if($row){
$_POST['word_description'] = $row['word_description'];
echo $_POST['word_description'];
}
}
if(isset($_POST['submit_word'])){
$word_name = $_POST['word_name'];
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
$result=mysqli_query($connection, $q2);
$count=mysqli_num_rows($result);
if($count==1){
echo 'Позна ве.';
}else{
echo 'Не позна ве.';
}
}
?>
<br><br><br>
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
</body>
</html>
I think you have some typos.
This line of code here:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
Should be like this:
$q2="SELECT * FROM words WHERE word_name='".$word_name."' and word_description='".$_POST['word_description']."'";
1) There is a typo in $_POST['word_description'] in your query:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
2) Also, I would recommend using the word_id instead of the word description to make the verification... you would need to write it in a <input name="word_id" type="hidden" value="..." /> in your form to pass it along.
What would be even better, to prevent people from knowing the answer by looking at the code (in case they would know what word matches what id), you could encode the value in the hidden field to be md5($word_id.$word_name) and then in your query you check "WHERE MD5(CONCAT(word_id, word_name))='".$_POST['word_md5']."'" (assuming your hidden input is now called "word_md5).
EDIT:
After looking at the HTML I see what your problem is:
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
This should all be in the same <form> element:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
When the form is submitted, the $_POST array should contain the word_description AND the word_name submitted.
EDIT 2:
If you wish to use the id, you would have to first add it to your SELECT query:
$q = mysqli_query($connection, ' SELECT word_id, word_description
FROM words ORDER BY rand() LIMIT 1
');
Then you'd need to set it to some variable, and then later in your HTML:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_id" value="<?php echo $word_id?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
Your second SQL query should then look like:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_id='".$_POST['word_id']."'";
Note: it is a bad practice to change the $_POST array in your code.
This array is populated by the request sent by the client and things can get confusing if you change the values there.
It is better to create another variable and set it to the value from the $_POST (example: $word_description = $_POST['word_description'];).
This way, you can still use array_key_exists('word_description', $_POST) to verify if the client actually sent something.
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']));
I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.
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>