Edit functionality not works Php MySql - php

This is the code for edit.php where when I click edit this page opens and edits that specific line.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body><?php // if there are any errors, display them
if ($error != ''){echo '
<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label><br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" /><br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b><br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" /><br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" /><br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" /><br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" /><br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" /><br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" /><br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back();return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php } // connect to the database
include('connect.php');// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])){// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])){// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$telephone_number = mysql_real_escape_string(htmlspecialchars($_POST['telephone_number']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$job_title = mysql_real_escape_string(htmlspecialchars($_POST['job_title']));
$workplace = mysql_real_escape_string(htmlspecialchars($_POST['workplace']));
$country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$nationality = mysql_real_escape_string(htmlspecialchars($_POST['nationality']));// check that firstname/lastname fields are both filled in
if ($name == ''){// generate error message
$error = 'ERROR: Please fill in all required fields!';//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else{// save the data to the database
$link->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");// once saved, redirect back to the view page
header("Location: view.php");
}
}
else{// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else{ // if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){// query db
$id = $_GET['id'];
$result = $link->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);// check that the 'id' matches up with a row in the databse
if($row){// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];// show form //renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else{// if no match, display result
echo "No results!";
}
}
else{// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
It gives first warning that mysql is deprecated so I used below syntax but still it gives error:
mysqli_real_escape_string(htmlspecialchars($link,$_POST['name']));
Second major error its giving is that it takes me to this error message and makes all form fields empty. The line its showing always is:
ERROR: Please fill in all required fields!
Please Guide!

$servername = "localhost:3306";
$username = "root";
$password = "<Password here>";
$dbname = "TUTORIALS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tutorials_inf(name)VALUES ('".$_POST["name"]."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
$conn->close();
}

I Solved My-Self...
Code Below...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<!--HTML form -->
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label>
<br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" />
<br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b>
<br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" />
<br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" />
<br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" />
<br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" />
<br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" />
<br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" />
<br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php
}
// connect to the database
$mysqli = new mysqli("sql213.byethost7.com", "b7_21234466", "mazhar2012", "b7_21234466_conference");
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = $mysqli->real_escape_string($_POST['name']);
//$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
//$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$telephone_number = $mysqli->real_escape_string($_POST['telephone_number']);
$email = $mysqli->real_escape_string($_POST['email']);
$job_title = $mysqli->real_escape_string($_POST['job_title']);
$workplace = $mysqli->real_escape_string($_POST['workplace']);
$country = $mysqli->real_escape_string($_POST['country']);
$nationality = $mysqli->real_escape_string($_POST['nationality']);
// check that firstname/lastname fields are both filled in
if ($name == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else
{
// save the data to the database
$mysqli->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = $mysqli->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];
// show form
//renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>

$link->query($conn,"UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");

Related

Displaying input error messages next to the input field

I would like to display error checking next to the input field. Currently, errors are displayed at the top of the page.
Maybe there is some way to check for input errors?
I could not find a similar example where html and php code are separated into different files
Or my code is completely wrong.
index.php
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>testpage</title>
</head>
<body>
<?php
require('process.php');
?>
<h1>Form</h1>
<form method="post" action="">
<div> Date : <input type="date" name="date"/><br />
</div>
<div>
<label>Start:</label>
<select name="starttime" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>End:</label>
<select name="endtime">
<option value="18:00:00">18:00</option>
</select>
<br>
</div>
<div>
Name : <input type="text" name="user_name" placeholder="Name" /><br />
</div>
Mail : <input type="email" name="user_email" placeholder="Mail" /><br />
Message : <textarea name="user_text"></textarea><br />
<input type="submit" value="Send" />
</form>
<h3 class=" txt_center">DB Output <span id="curdate">
<?php require('calendar.php');
?>
<!-- <script type="text/javascript" src="js/time-select.js"></script> -->
</body>
</html>
process.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
$u_starttime = $_POST["starttime"];
$u_endtime = $_POST["endtime"];
$u_name = filter_var($_POST["user_name"]);
$u_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$u_text = filter_var($_POST["user_text"]);
$error = array();
if (empty($u_date)){
$error['date'] = 'Date is empty!';
}
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
elseif (empty($u_name)){
echo "Name is empty.";
}
else{
require_once('db-connect.php');
$statement = $mysqli->prepare("INSERT INTO users_data (date, start_time, end_time, user_name, user_email, user_message) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssss', $u_date, $u_starttime, $u_endtime, $u_name, $u_email, $u_text);
if($statement->execute()){
print "Hello, " . $u_name . "!, request is complete!";
}else{
print $mysqli->error;
}
}
}
?>
You can add the 'required' attribute to <input> elements, which get validated on form submission. E.g. <input type="date" name="date" required/> eliminating the necessity to write code for error output.
EDIT: here you can see how the warning is shown
Also, the validation
elseif ( $u_starttime > $u_endtime ){
echo "*Incorrect time";
}
is not required, since the user's choices already force starttime < endtime.
Cheers
Here is an example for setting date validation next to your date input fields.
in process.php:
` $errordate="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$u_date = filter_var($_POST["date"]);
if (empty($u_date)){
$errordate= 'Date is empty!';
}}
and in your index.php:
<input type="date" name="date"/> * <?php echo "<p style='color:red;'>".$errordate . "</p>"; ?>

Php - isset() condition doesn't work

I am a newbie to PHP. & My PHP Code doesn't work, I want to update some date using MySQL but it seems that first IF condition is 'false' i don't why, I am using PHP 7 & XAMP as a local host, Dreamweaver as an IDE & this is my code:
if(isset($_POST["btn_edit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
if(!empty($_FILES["img"]["name"]))
{
$img = $_FILES["img"]["name"];
$img_temp = $_FILES["img"]["tmp_name"];
if(move_uploaded_file($img_temp, "assets/images/".$img))
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
$result = header("Location:index.php");
}
else
{
echo mysql_error();
}
}
}
else
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
echo "<h5>Updated</h5>";
}
}
}
it showing me nothing just refresh the page & this is HTML CODE:
<form method="post" enctype="multipart/form-data">
<input name="name" value="<?php echo $name ?>" />
<input name="email" value="<?php echo $email ?>" />
<input name="password" value="<?php echo $password ?>" />
<img width="50" height="50" src="<?php echo 'assets/images/'.$row[4] ?>" />
<input name="img" type="file" class="text-info" required="required" />
<br/>
<input name"btn_edit" type="submit" />
<?php if(isset($_POST["btn_edit"])) echo $result ?>
You have syntax issue in your button HTML.
This:-
<input name"btn_edit" type="submit" />
Need to be:-
<input name="btn_edit" type="submit" /><!-- = is missing in name -->

Updating post with PHP & MySQL

I'm building a sort of blog system, but I'm having trouble with editing an existing 'post' in the system. It is collecting the data from the database, and it displays it. But when I click the update button, I get this error. I've looked for it, checked my code couple of times, but I just couldn't find anything. This is the error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
And this is my code.
<?php //include config
require_once('../../includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bewerk</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="../style/normalize.css">
<link rel="stylesheet" href="../style/main.css">
<link rel="stylesheet" href="../style/login.css">
</head>
<body>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT patient_id, voornaam, achternaam, leeftijd, lengte, gewicht, foto_url FROM patienten WHERE patient_id = :patient_id') ;
$stmt->execute(array(':patient_id' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare('UPDATE patiënten SET patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
':patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
//redirect to index page
header('Location: index.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<div class="row">
<div class="col-md-2 col-md-offset-5">
<img src="../style/images/logo.png">
</div>
</div>
<div class="keuze_link row">
<p><b><?php echo $row['voornaam'];?> <?php echo $row['achternaam'];?></b> bewerken</p>
</div>
<div class="container">
<form class="toevoegen" action="" method="post">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];? >">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
</div>
</body>
</html>
If you guys wanna know more, or see more code, I'd like to hear it. Thanks in advance.
EDIT. for update.
//insert into database
$stmt = $db->prepare('UPDATE patienten SET patient_id = :patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
'patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
Latest form for update
<form class="toevoegen" action="" method="post">
<input type="hidden" name="voornaam" value="<?php echo $row['patient_id'];?>">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];?>">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
:patient_id is missing from the $stmt->execute() function. Please add it and try again.
In your update query you forgot about :patient_id to bind
And yes, remove $ before column names.

Set page to display dropdown menu when editing data with PHP and MySQLi

I have made a page for registering hardware, with 2 drop-down menus, which work.
The page looks like this:
<!DOCTYPE HTML>
<html>
<head>
<title>Registrer ny hardware</title>
</head>
<body>
Her registreres ny hardware. Udfyld formularen herunder og tryk gem. <br>
<form action="Registerhardware.php" method="post">
<!-- VARCHAR -->
Serienr: <br>
<input type="text" name="Series"> <br>
<!-- VARCHAR -->
Mærke: <br>
<select id="Brand" name="Brand">
<?php
include('Mysql.php');
$conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sql = "SELECT Brand FROM hardware";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$Brand=$row["Brand"];
echo "<option>
$Brand
</option>";
}
?>
</select>
<br>
<!-- <input type="text" name="Brand"> <br> -->
<!-- VARCHAR -->
Model: (* <a href=Registernymodel.php>Ny model - læg den ind her først</a>)<br>
<select id="Model" name="Model">
<?php
// include('Mysql.php');
// $conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sqlm = "SELECT Model FROM hardware";
$resultm = $conn->query($sqlm);
while($rowm = $resultm->fetch_assoc())
{
$Model=$rowm["Model"];
echo "<option>
$Model
</option>";
}
?>
</select>
<br>
<!-- VARCHAR -->
Detaljer: <br>
<input type="text" name="Detaljer"> <br>
<!-- VARCHAR -->
Indkøbsdato (yyyy-dd-mm): <br>
<input type="date" name="Date"> <br>
<!-- VARCHAR -->
Leverandør: <br>
<input type="text" name="Firm"> <br>
<!-- VARCHAR -->
Hardwarenavn: <br>
<input type="text" name="Hardwarename"> <br>
<!-- VARCHAR -->
<!-- INT -->
Stregkode: <br>
<input type="number" name="Barcode"> <br>
<!-- VARCHAR -->
Placering: <br>
<input type="text" name="Place"> <br><br>
<!-- ENUM -->
SIMKort: <br>
<input type="radio" name="SIMCard" value="Ja">Ja
<input type="radio" name="SIMCard" value="Nej" checked>Nej<br><br>
<!-- ENUM -->
På lager: <br>
<input type="radio" name="Stock" value="Ja" checked>Ja
<input type="radio" name="Stock" value="Nej">Nej<br><br>
<!-- ENUM -->
Udlånes: <br>
<input type="radio" name="Borrow" value="Ja" >Ja
<input type="radio" name="Borrow" value="Nej" checked>Nej<br><br>
<!-- TEXT -->
Kommentarer: <br>
<textarea name="Comments" style="width: 200px; height: 50px;"> </textarea> <br>
<input type="submit" value="Gem og send mail">
</form>
</body>
</html>
But now I'm trying to edit data from one post in the table, but the first drop-down menu doesn't have any data and the form stops there.
The page looks like this:
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("Mysql.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($Serienr = '', $Hardwarenavn ='', $error = '', $IDNr = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($IDNr != '') { echo "Edit Record"; } else { echo "New Record"; } ? >
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($IDNr != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($IDNr != '') { ?>
<input type="hidden" name="IDNr" value="<?php echo $IDNr; ?>" />
<p>IDNr: <?php echo $IDNr; ?></p>
<?php } ?>
<strong>IDNr: *</strong> <input type="text" name="IDNr"
value="<?php echo $IDNr; ?>"/><br/>
<strong>Serienummer: *</strong> <input type="text" name="Series"
value="<?php echo $Serienr; ?>"/><br/>
<strong>Mærke: *</strong>
<select id="Brand" name="Brand">
<?php
include('Mysql.php');
$conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sql = "SELECT Brand FROM hardware";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$Brand=$row["Brand"];
echo
"<option>
$Brand
</option>";
}
?>
</select>
<br>
<br/>
<strong>Model: *</strong>
<select id="Model" name="Model">
<?php
// include('Mysql.php');
// $conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sqlm = "SELECT Model FROM hardware";
$resultm = $conn->query($sqlm);
while($rowm = $resultm->fetch_assoc())
{
$Model=$rowm["Model"];
echo "<option>
$Model
</option>";
}
?>
</select>
<br>
<br/>
<strong>Detaljer: *</strong> <input type="text" name="Detaljer"
value="<?php echo $Detaljer; ?>"/><br/>
<strong>Dato: *</strong> <input type="date" name="Date"
value="<?php echo $Date; ?>"/><br/>
<strong>Leverandør: *</strong> <input type="text" name="Firm"
value="<?php echo $Firm; ?>"/><br/>
<strong>Hardwarenavn: *</strong> <input type="text" name="Hardwarename"
value="<?php echo $Hardwarenavn; ?>"/><br/>
<strong>Stregcode: *</strong> <input type="number" name="Barcode"
value="<?php echo $Barcode; ?>"/><br/>
<strong>Lokation: *</strong> <input type="text" name="Place"
value="<?php echo $Placering; ?>"/><br/>
<strong>SIMKort: *</strong> <input type="radio" name="SIMCard"
value="<?php echo $SIMKort; ?>"/><br/>
<strong>Lager: *</strong> <input type="radio" name="Stock"
value="<?php echo $Stock; ?>"/><br/>
<strong>Udlånes: *</strong> <input type="radio" name="Borrow"
value="<?php echo $Udlaan; ?>"/><br/>
<strong>Kommentarer: *</strong> <input type="text" name="Comments"
value="<?php echo $Kommentarer; ?>"/><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['IDNr']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['IDNr']))
{
// get variables from the URL/form
$IDNr = $_POST['IDNr'];
$Serienr = htmlentities($_POST['Series'], ENT_QUOTES);
$Brand = htmlentities($_POST['Brand'], ENT_QUOTES);
$Model = htmlentities($_POST['Model'], ENT_QUOTES);
$Detaljer = htmlentities($_POST['Detaljer'], ENT_QUOTES);
$Date = htmlentities($_POST['Date'], ENT_QUOTES);
$Firm = htmlentities($_POST['Firm'], ENT_QUOTES);
$Hardwarenavn = htmlentities($_POST['Hardwarename'], ENT_QUOTES);
$Barcode = htmlentities($_POST['Barcode'], ENT_QUOTES);
$Placering = htmlentities($_POST['Place'], ENT_QUOTES);
$SIMKort = htmlentities($_POST['SIMCard'], ENT_QUOTES);
$Stock = htmlentities($_POST['Stock'], ENT_QUOTES);
$Udlaan = htmlentities($_POST['Borrow'], ENT_QUOTES);
$Kommentarer = htmlentities($_POST['Comments'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($Serienr == '' || $Hardwarenavn == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($Serienr, $Hardwarenavn, $error, $IDNr);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $conn->prepare("UPDATE registrering SET Series = ?, Hardwarename = ?
WHERE IDNr=?"))
{
$stmt->bind_param("ssi", $Serienr, $Hardwarenavn, $IDNr);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['IDNr']) && $_GET['IDNr'] > 0)
{
// get 'id' from URL
$IDNr = $_GET['IDNr'];
// get the record from the database
$conn = new mysqli($server, $user, $password, $database);
if($stmt = $conn->prepare("SELECT * FROM registrering WHERE IDNr=?"))
{
$stmt->bind_param("i", $IDNr);
$stmt->execute();
$stmt->bind_result($IDNr, $Serienr, $Brand, $Model, $Detaljer, $Date, $Firm, $Hardwarenavn, $Barcode, $Placering, $SIMKort, $Stock, $Udlaan, $Kommentarer);
$stmt->fetch();
// show the form
renderForm($Serienr, $Hardwarenavn, NULL, $IDNr);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: view.php");
}
}
}
/*
NEW RECORD:
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$IDNr = $_POST['IDNr'];
$Serienr = htmlentities($_POST['Series'], ENT_QUOTES);
$Brand = htmlentities($_POST['Brand'], ENT_QUOTES);
$Model = htmlentities($_POST['Model'], ENT_QUOTES);
$Detaljer = htmlentities($_POST['Detaljer'], ENT_QUOTES);
$Date = htmlentities($_POST['Date'], ENT_QUOTES);
$Firm = htmlentities($_POST['Firm'], ENT_QUOTES);
$Hardwarenavn = htmlentities($_POST['Hardwarename'], ENT_QUOTES);
$Barcode = htmlentities($_POST['Barcode'], ENT_QUOTES);
$Placering = htmlentities($_POST['Place'], ENT_QUOTES);
$SIMKort = htmlentities($_POST['SIMCard'], ENT_QUOTES);
$Stock = htmlentities($_POST['Stock'], ENT_QUOTES);
$Udlaan = htmlentities($_POST['Borrow'], ENT_QUOTES);
$Kommentarer = htmlentities($_POST['Comments'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($Serienr == '' || $Hardwarenavn == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($Serienr, $Hardwarenavn, $error);
}
else
{
// insert the new record into the database
if ($stmt = $conn->prepare("INSERT rgistrering (Series, Hardwarename) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $Serienr, $Hardwarenavn);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$conn->close();
?>
What have I done wrong?

Derive checkbox state from non-boolean MySQL with PHP

Currently I have a form that makes use of fields and check boxes. The fields and checkboxes both update the database perfectly:
<?php
function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags )
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
. . .
. . .
if(count($articletags) > 0)
{
$articletags_string = implode(",", $articletags);
}
if (isset($_POST['submit']))
{
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
. . .
mysql_query("INSERT articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' ")
or die(mysql_error());
// once saved, redirect to success page
header("Location:addsuccess.html");
}
}
else
{
renderForm('','','','');
}
?>
Now, though, I'm wondering if I should have gone with a boolean checkbox instead.
The reason is that I've built an edit form as well and it follows the new entry form exactly except that values are already filled in via the MySQL DB.
So, I'm assuming that it would be considerably easier to use boolean, right?
So, instead of using an array, I should give the checkboxes different names, and on the edit.php page I can use something like:
<?php
function renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<h1>Edit Details for <?php echo $articletitle; ?></h1>
<fieldset>
<legend>Article details</legend>
<div class="row">
<div class="field"><label>Article Title</label><input type="text" name="articletitle" value="<?php echo $articletitle; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Author </label><input type="text" name="articleorganization" value="<?php echo $articleorganization; ?>"/></div>
<div class="field"><label>Article Date </label><input type="text" name="articledate" value="<?php echo $articledate; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Url: </label><input type="text" name="articleurl" value="<?php echo $articleurl; ?>"/></div>
<div class="row">
<input type="checkbox" name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" name="articletags2" value="checkbox 2" id="articletags_1" />
</div>
</fieldset>
<footer><input type="submit" name="submit" value="Submit"></footer></form>
</div>
</body>
</html>
<?php
}
include('settings.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
if ($articletitle == '' || $articletags == '')
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($id, $articletitle, $articletags);
}
else
{
mysql_query("UPDATE articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' WHERE id=$id")
or die(mysql_error());
header("Location: editsuccess.html");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM articles WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$articletitle = $row['articletitle'];
$articleorganization = $row['articleorganization'];
$articledate = $row['articledate'];
$articleurl = $row['articleurl'];
$articletags = $row['articletags'];
renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
The problem with that though is that my checkboxes on the edit.php page still aren't showing the checked state.
You need to use checked="checked" in the same way as you used for value. See the solution bottom:
<input type="checkbox" <?php if(isset($_POST[articletags1])) echo 'checked="checked" ' ?>name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" <?php if(isset($_POST[articletags2])) echo 'checked="checked" ' ?>name="articletags2" value="checkbox 2" id="articletags_1" />
Hope this works. Updated the right code. Use ini_set('display_errors', 1); to get the error generated.

Categories