checkbox value to mysql/php - php

im triyng to figure out a problem for days and have some progress but im stuck with some checkbox page.
So the "project" is some kind of "online car stand" and im stuck in the insert car part.
I got the html and php for insert a car into the sql table.
Then after the car i have a link to insert extras of the car, like abs,cruise control, gps ...etc...
The Html is something like this:
<?php
include "verifica.php";
?>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Stand Automovel
</title>
</head>
<body>
<form action="extras.php" method="POST">
<P class="style2"style2"> Extras:
<div class="style2">
<input type="checkbox" name="chk" value="1">GPS<br>
<input type="checkbox" name="chk" value="2">ABS<br>
<input type="checkbox" name="chk" value="3">Computador De Bordo<br>
<input type="checkbox" name="chk" value="4">Ar Condicionado<br>
</div>
<P> </P>
<P><INPUT TYPE=submit VALUE="Submeter"> <INPUT TYPE=reset VALUE="Limpar"> </P>
<P> </P>
</form>
</body>
The php page code is this one:
<html>
<head>
<meta charset="UTF-8">
<title>Inserir Automoveis</title>
</head>
<body>
<?php
include "connect.php";
$sql = "INSERT INTO extra (extra.id_carro,extra.id_lista_extra) SELECT carro.id_extras , ? FROM carro,lista_extra,extra ORDER BY carro.id_carro DESC LIMIT 1";
if($teste= $mysqli->prepare($sql)) {
$teste->bind_param("s",$_REQUEST["extra.id_lista_extra"]);
$teste->execute();
if ($teste>affected_rows == -1) {
echo $print;
echo "<p>". $mysqli->error. "</p>";
}
else {
echo "<sp>Carro inserido com sucesso!</p>";
}
}
?>
The goal with that $sql is to get the last id from last car inserted on row cars and add 1 extra to him passed by the check box.
i have tried just with 1 box because i read that if a checkbox was unchecked pass "null"argument.
I tried already with diferent aproaches. My final goal is create a for cicle that creates the number of rows in table extra for each number of extra checked in my checkbox.
(i tried something like this but with no sucess)
$checkbox1 = $_POST['chk'];
if($_POST["Submit"]=="Submit"){
for ($i=0;$i<sizeof ($checkbox1)$i++){
$sql = "INSERT INTO extra (id_lista_extra) values('".$checkbox1[$i]."')";
mysql_query($sql) or die(mysql_error());
}
}
i got some php errors on that $i .
If someone can give me a hint i would appreciate.
Thanks

Here is an example all you would have to do is change the names inside these $_POST variables as well as change your HTML checkbox names to have a [] after them. e.g
<input type="checkbox" name="chk[]" value="1">GPS<br>
<input type="checkbox" name="chk[]" value="2">ABS<br>
$cat_array = array();
if(isset($_POST['chk'])){
if(is_array($_POST['chk'])) {
foreach($_POST['chk'] as $value){
array_push($cat_array, $value);
}
}else{
$value = $_POST['chk'];
array_push($cat_array, $value);
}
}
Now all these values are in an ARRAY. Do as you please with them, loop through them, call them by there indexes, etc..

Related

HTML / Ajax / PHP - how to check if/which checkboxes are checked, and perform an different action for each one

As above, I"m trying to create a simple html / PHP page. When the submit button is clicked, I would like different SQL code to be run depending on which of the checkboxes is checked. The SQL code is pretty simple, its just displaying a different table for each checkbox, but I'm not sure how to check if the checkboxes are checked. My HTML code is below
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ricky Deacon, CSIS3380 Assignment 3. Show Table.html</title>
</head>
<body>
<h1>Book-O-Rama Catalog Search</h1>
<form action="showtab.php" method="post">
<fieldset><legend>Which Tables Would You Like To View?</legend>
<p>
Customers
<input type="checkbox" name="table" value="cust"/>
Orders
<input type="checkbox" name="table" value="ord"/>
Order Items
<input type="checkbox" name="table" value="itms"/>
Books
<input type="checkbox" name="table" value="book"/>
Book Reviews
<input type="checkbox" name="table" value="brev"/> <br /><br />
<input type="submit" name="submit" value="Show Tables">
</p>
</fieldset>
</form>
</body>
I haven't written the PHP response yet as I am not sure where to start
Thanks
Here is a more complete answer of what you'd need to do:
Edited - Also included what your inputs need to look like.
<input type="checkbox" name="table[]" value="cust"/>Orders
<input type="checkbox" name="table[]" value="ord"/>Order Items
<input type="checkbox" name="table[]" value="itms"/>Books
<input type="checkbox" name="table[]" value="book"/>Book Reviews
<input type="checkbox" name="table[]" value="brev"/>
<?php
// Check that the values you're trying to access have actually been posted
// 'table' is the 'name' of your input
if (!empty($_POST['table'])) {
// If it's not empty then set the variable
$tables = $_POST['table'];
}
// If it is empty (Your form didn't submit this input)
else {
// end processing or return to the previous page
return false;
}
// You will now need to loop through the array
foreach ($tables as $table) {
switch($table) {
case 'cust':
// Run Cust SQL Query
break;
case 'ord':
// Run ord SQL Query
break;
case 'itms':
// Run itms SQL Query
break;
case 'book':
// Run book SQL Query
break;
case 'brev':
// Run brev SQL Query
break;
}
}
?>
And for reference why it's better to use a switch case instead of if/else in this situation:
Is "else if" faster than "switch() case"?
You can check whether a checkbox is checked in showtab.php. The 'value' attribute of the input will be posted to the 'name' attribute when the form is submitted. If the checkbox is blank it will post nothing.
<?php
if(isset($_POST['table']) && $_POST['table'] == 'cust') {
// Show table here
}
else {
// Do something else here.
}
?>
Your checkboxes will need unique names.
Hello can get all checked values with $_POST['table'] in your showtab.php.

PHP dynamic form will not INSERT into mySql

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>';.

How to show results of a form upon submission

Using WordPress, so PHP, HTML, CSS, JavaScript what is the best method of populating the results of a form upon submission? I could have a form with ddl, radio buttons, etc.
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
What is the best way of populating the results i.e. "67% of users are Female" and "30% ride bikes" on the same page once the submit button is triggered?
Try something along these lines:
script.php
----------
<html>
<body>
<form method=post action=script.php>
your form here...
</form>
<? if($_SERVER["CONTENT_LENGTH"]>0) {
//form was submitted to script, so process form inputs here and display results...
}
?>
</body>
</html>
<form action="phpfile.php" method="Post">
...form here
</form>
phpfile.php:
<?php
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}//etc..
//To show the result, simply echo it:
echo $sex;
You'll need some sort of storage system to be able to calculate the amount of each.
So what you would need to do is write a simple query where the value of the field is male or female. Then you can easily calculate it.
What you will need to do is add the form results to the database, then find the total number of results for both categories, then calculate the percent female and the percent bike.
The form page:
<html>
<?php
if(isset($_GET['status']) && $_GET['status'] == "values") {
//connect to DB and select table
$male = count( mysql_query("SELECT gender FROM Table WHERE gender='male'"));
$female = count (mysql_query("SELECT gender FROM Table WHERE gender='female'"));
$car = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='car'"));
$bike = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='bike'"));
$totalResults = $male + $female;
$totalVehicles = $car + $bike;
$percentFemale = 100 * ($female / $totalResults);
$percentFemale = number_format($percentFemale, 0);
$percentBike = 100 * ($bike / $totalVehicals);
$percentBike = number_format($totalBike, 0);
echo "<p>" . $percentFemale . "% of users are female. </p>";
echo "<p>" . $percentBike . "% of users use bikes. </p>";
} else { ?>
<form action="formProcessor.php" method="POST"><!-- You could also use GET -->
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
<?php } ?>
</html>
The formProcessor.php Page:
<?php
if(isset($_POST["sex"]) && isset($_POST['vehicle'])) {
//Connect to MySQL DB and select table here
$sex = $_POST['sex'];
$vehicle = $_POST['vehicle'];
mysql_query("INSERT INTO Table(sex, vehicle) VALUES($sex, $vehicle)"); //You may also want to add an id column, but...
//Close mysql connection
header("Location: /form.php?status=values");
die();
} else {
die("There was an error in your submission.");
}
?>
I think this answers your question, you've got a way to find the percent of female users and users on bikes. If you need that to be dynamic and show only the greater amount (or show both or something) just add a comment. This also assumes you are not using PDO, if you are, I can adjust the code. I just wrote the code, so I don't know for sure if it works, but here you go!

PHP Form using an array

Let me present my code first:
<?php include ('header.php'); ?>
<h3>Extra menu items , van eigen pagina's</h3>
<!-- zet menu onderdelen aan of uit -->
<?php
if ($_POST['submit'] == 'Verzenden') {
$checkbox_vals = $_POST['np_menu_active_post']; // This will pass the selected checkbox values as an array
//if(count($checkbox_vals) > 0) {
// Loop it and update the values in DB
foreach( $checkbox_vals as $key ){
$updatequery = "UPDATE custompage set np_menu_active = '$key'";
mysql_query($updatequery) or die("Couldn't get file list");
}
//}
?>
<meta HTTP-EQUIV="Refresh" CONTENT="0"; URL="<?php echo $_SERVER['PHP_SELF'];?>">
<?php
}
?>
<?php
$dbQuery_custom_toggle = "SELECT * ";
$dbQuery_custom_toggle .= "FROM custompage";
$result_custom_toggle = mysql_query($dbQuery_custom_toggle) or die("Couldn't get file list");
while($row = mysql_fetch_array($result_custom_toggle)) {
// $nptitel = $row['np_titel'];
// $nptekst = $row['np_tekst'];
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="hidden" name="np_menu_active_post[]" value="0" />
<?php echo $row['np_menu_titel'];?> <input type="checkbox" name="np_menu_active_post[]" value="1" <?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> /> <br />
<?php
}
?>
<input type="Submit" name="submit" value="Verzenden" class="btn-primary">
</form>
<!-- einde menu toggles -->
<br />
<br />
So im trying to make this form write the 1 value or 0 value based upon the checkboxed to the mysql db.
Its partly working, when i select the last checkbox, it checks all, and writes that to the db.
With the foreach loop you update your db in the same field with each checkbox, so the last checkbox is the only thing that is left.
Depending on the desired result, you need to differ the column (so np_menu_active) for each checkbox, or need to add a WHERE condition (as Rick said) to differ the row.
E.g. If you would like to save the checkbox settings for multiple users, you would create a column for each checkbox and a row for each user.

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