How to allow access to sql database from website using php code - php

I am receiving the following error on my website when I click the 'add record to database':
Database error while attempting to add record: INSERT command denied to user 'leaBoss'#'localhost' for table 'products'
I am assuming and this is where I could be totally incorrect that I need to adjust my database to accept the INSERT command. I think this is done as my database shows:
image is of privleges in my database
I am using the first one, leaBoss at localhost and it shows 'all privedges'
My connection code file is as follows:
<?php
// Connection for admin user
if(!defined('ALLOW_ACCESS'))
die('Direct access to this file is not allowed');
// Information required to connect to MySQL database
define ('DB_HOST', 'localhost');
define ('DB_USER', 'leaBoss');
define ('DB_PASSWORD', 'assessment');
define ('DB_NAME', 'dbleaparker');
// connect to the database
$db = #new mysqli (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check whether the connection worked...
if (mysqli_connect_errno()) {
print '<br />Can\'t connect to database. Please try again later.';
exit;
}
?>
And the addProduct file which is where the error comes up for the webpage:
<?php
define('ALLOW_ACCESS', 1); //define a constant to give permission to use include files
$title = 'Add a product';
require('../../incAdmin/incHead.php');
require_once('../../incAdmin/adminConnect.php');
?>
<h2>Add a new product to the Leas Japan Art</h2>
<?php
if ($_SESSION['loggedIn']) {
if (isset($_POST['cmdSubmit'])) {
// CREATE VARIABLES from form's POST data
$categoryID = $_POST['cboCategoryID'];
$productID = $_POST['txtProductID'];
$pName = $_POST['txtName'];
$pPrice = $_POST['txtPrice'];
$pImage = $_POST['txtImage'];
// VALIDATE THE FORM (this is very basic - you could make the validation more comprehensive)
$message = '';
if (empty($productID)) {
$message = "ERROR: Please enter a product ID number";
}
if (empty($pName)) {
$message = $message . "\nERROR: Please enter the product name";
}
// If no errors, write the record to database
if ($message == '') {
$sql = "INSERT INTO category . Products (categoryID, productID, pName, pPrice, pImage) VALUES ('$categoryID','$productID','$pName','$pPrice','$pImage')";
if ($stmt = $db->prepare($sql)) {
$stmt->execute();
$stmt->close();
$message = 'Record has successfully been added to database';
}
else {
// an error has occurred, so the statement wasn't executed
print 'Database error while attempting to add record: ' . $db->error;
}
}
}
else { // this is the first time form will be displayed. Initialise variables.
$categoryID = '';
$productID = '';
$pName = '';
$pPrice = '';
$pImage = 'placeholder.jpg';
$message = '';
}
?>
<form id="frmAddProduct" method="post" action="addProduct.php">
<p><br />
<label>Category:</label>
<select name="cboCategoryID">
<?php
//Set up a drop-down list of categories
$stmt = $db->prepare('SELECT * FROM Category ORDER BY cName');
$stmt->execute();
$stmt->bind_result($OUTPUTcategoryID, $OUTPUTcName);
// while setting up the drop-down list, retain any PREVIOUSLY SELECTED option
while ($stmt->fetch() ) {
print '<option ';
if ($OUTPUTcategoryID == $categoryID) { print 'selected '; }
print 'value="';
print $OUTPUTcategoryID;
print '">';
print $OUTPUTcName;
print '</option>';
}
$stmt->close();
?>
</select>
<br /><br />
<label>Product ID :</label>
<input type="text" name="txtProductID" id="txtProductID" size="8" value="<?php print $productID; ?>" />
<br /><br />
<label>Product Name:</label>
<input type="text" name="txtName" id="txtName" size="70" value="<?php print $pName; ?>" />
<br /><br />
<label>Product price:     $</label>
<input type="text" name="txtPrice" id="txtPrice" size="8" value="<?php print $pPrice; ?>" />
<br /><br />
<label>Image filename:</label>
<input type="text" name="txtImage" id="txtImage" size="30" value="<?php print $pImage; ?>" />
<em>(must include file extension, eg seascape.jpg)</em><br /><br />
<input type="submit" name="cmdSubmit" id="cmdSubmit" value="Add record to database" />
<br /><br />
<label>Report:</label>
<textarea name="txtMessage" id="txtMessage" cols="60" rows="4" readonly="readonly"
style="background-color:#FFF;color:#000; overflow:hidden;"><?php print $message;?></textarea>
</p>
</form>
<!----------------------------------------------------------------------------->
<?php
}
else {
print 'ERROR: you are not authorised to access this page';
}
require('../../incAdmin/incFoot.php');
?>
Thank you in advance to anyone who is able to suggest something.

Related

Edit functionality not works Php MySql

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");

Populate drop down list, pass two variables

I am wanting to populate a drop down list from another mysql table and then assign the values from two of the columns into variables - i.e. "select name, eid, perc from employee". "John Doe" would be $eid = 1234 and $perc = 20.
Any help with this would be greatly appreciated!
Thank you - Matt
Here is the code I have been working with:
PHP
<?php
//session_start();
$page_title = 'New invoice';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('mysqli_connect.php'); // Connect to the db.
/*$errors = array(); // Initialize an error array. */
// Invoice number is automatic
if (empty($_POST['op1'])) {
$errors[] = 'Operation needs to be entered.';
} else {
$op1 = mysqli_real_escape_string($dbc, trim($_POST['op1']));
}
// Amount:
if (empty($_POST['amount1'])) {
$errors[] = 'Amount to be charged.';
} else {
$amount1 = mysqli_real_escape_string($dbc, trim($_POST['amount1']));
}
// percentage:
if (empty($_POST['perc'])) {
$errors[] = 'Select a percentage.';
} else {
$perc = mysqli_real_escape_string($dbc, trim($_POST['perc']));
}
// eid:
if (empty($_POST['eid'])) {
$errors[] = 'Enter a techician.';
} else {
$eid = mysqli_real_escape_string($dbc, trim($_POST['eid']));
}
// Stocknum:
if (empty($_POST['stocknum'])) {
$errors[] = 'Need a stock number.';
} else {
$stocknum = mysqli_real_escape_string($dbc, trim($_POST['stocknum']));
}
// Stocknum:
if (empty($_POST['myear'])) {
$errors[] = 'Enter vehicle year.';
} else {
$myear = mysqli_real_escape_string($dbc, trim($_POST['myear']));
}
if (empty($_POST['make'])) {
$errors[] = 'Enter vehicle make.';
} else {
$make = mysqli_real_escape_string($dbc, trim($_POST['make']));
}
if (empty($_POST['model'])) {
$errors[] = 'Enter vehicle model.';
} else {
$model = mysqli_real_escape_string($dbc, trim($_POST['model']));
}
if (empty($_POST['vin'])) {
$errors[] = 'Enter last 6 of the VIN.';
} else {
$vin = mysqli_real_escape_string($dbc, trim($_POST['vin']));
}
if (empty($_POST['mileage'])) {
$errors[] = 'Enter current mileage.';
} else {
$mileage = mysqli_real_escape_string($dbc, trim($_POST['mileage']));
}
if (empty($errors)) { // If everything's OK.
$q = "INSERT INTO `mwcc`.`wp` (`tdate`, `stocknum`, `myear`, `make`, `model`,`vin`, `eid`, `op1`, `amount1`,`mileage`,`ecomm`) VALUES (CURRENT_DATE(), '$stocknum', '$myear', '$make', '$model','$vin', '$eid', '$op1', '$amount1','$mileage', ($amount1*$perc));";
$r = #mysqli_query ($dbc, $q); // Run the query.
//echo ($q);
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Success!</h1>
<p>Invoice has been created!<br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">Uh oh. There has been an error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
HTML :
<form action="newinv.php" method="post">
<p>Stock #
<input type="text" name="stocknum" size="15" maxlength="20" value="<?php if (isset($_POST['stocknum'])) echo $_POST['stocknum']; ?>" />
Last 6 of VIN
<input type="text" name="vin" size="15" maxlength="6" value="<?php if (isset($_GET['vin'])) echo $_POST['vin']; ?>" /> </p>
<p>Year
<input type="text" name="myear" size="4" maxlength="4" value="<?php if (isset($_POST['myear'])) echo $_POST['myear']; ?>" />
Make
<input type="text" name="make" size="30" maxlength="20" value="<?php if (isset($_POST['make'])) echo $_POST['make']; ?>" />
Model
<input type="text" name="model" size="30" maxlength="20" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" /></p>
Mileage
<input type="text" name="mileage" sizesize="15" maxlength="6" value="<?php if (isset($_POST['mileage'])) echo $_POST['mileage']; ?>" /> </p>
<p>Operation <input type="text" name="op1" size="60" maxlength="250" value="<?php if (isset($_POST['op1'])) echo $_POST['op1']; ?>" />
Amount <input type="text" name="amount1" size="8" maxlength="20" value="<?php if (isset($_POST['amount1'])) echo $_POST['amount1']; ?>" /></p>
<br>
<input type="radio" name="eid" value="1767">Alex H<br>
<input type="radio" name="eid" value="1688">Blake S<br>
<input type="radio" name="eid" value="1506">Brian M<br>
<input type="radio" name="eid" value="1898">Chris V<br>
<input type="radio" name="eid" value="3000">Kim R<br>
<input type="radio" name="eid" value="1916">Jorden U<br>
<input type="radio" name="eid" value="1931">Tina M<br>
<input type="radio" name="eid" value="1506">Tanner C<br>
<br>
<input type="radio" name="perc" value=".35">35%
<br>
<input type="radio" name="perc" value=".40">40%
<p><input type="submit" name="submit" value="Add" /></p>
</form>
My understanding from your question.
Get query result as you mentioned.select name, eid, perc from employee
For Front End if you want pass both values in single select then use some unique separator like i'm using double underscore __
<?php foreach($result as $user): ?>
<select name="eid__perc" >
<option value="<?php $user->eid . '__' . $user->perc?>">
<?php $user->name; //in array case $user['name'];?>
<option>
<select>
<?php endforeach;?>
And when you save information use same separator to explode data like
list($eid, $perc) = explode('__', $_POST['eid__per'])
You need to use WHERE condition for that:
SELECT name, eid, perc FROM employee WHERE eid = ? AND perc = ?
Than use mysqli_stmt_bind_param($stmt, 'ss', $eid, $perc); to bind parameters.

Update function php

I'm working in a update file using php and mysql but the update function doesn't work. I wrote the code using an example and modified according to the requirements. The file does work and doesn't really drop any error but it doesn't change anything in the database. It is suppose to update a book database.
Code:
<?php
$page_title = 'Add Books';
include ('bookincludes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize an error array.
if (empty($_POST['title'])) {
$errors[] = 'Please add title.';
} else {
$e = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['author'])) {
$errors[] = 'Please add the name of the author.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['author']));
}
if (!empty($_POST['isbn1'])) {
if ($_POST['isbn1'] != $_POST['isbn2']) {
$errors[] = 'ISBN number does not match.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['isbn1']));
}
} else {
$errors[] = 'You need to enter ISBN number.';
}
if (empty($errors)) { // If everything's OK.
$q = "SELECT ISBN FROM Books WHERE (Title='$e' AND Author ='$p')";
$r = #mysqli_query($dbc, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = $row[0] ";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message.
echo '<h1>Thank you!</h1>
<p>Thank you, Book has been added or modified</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">System error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script (to not show the form).
include ('includes/footer.html');
exit();
} else {
echo '<h1>Error!</h1>
<p class="error">ISBN number is incorrect.</p>';
}
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
<h1>Update</h1>
<form action="Bupdate.php" method="post">
<p>ISBN number: <input type="text" name="isbn1" size="20" maxlength="60" value="<?php if (isset($_POST['isbn1'])) echo $_POST['isbn1']; ?>" /> </p>
<p>Confirm ISBN: <input type="text" name="isbn2" size="20" maxlength="60" value="<?php if (isset($_POST['isbn2'])) echo $_POST['isbn2']; ?>" /> </p>
<p>Author: <input type="text" name="author" size="20" maxlength="60" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Title: <input type="text"" name="title" size="20" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
<p>Year: <input type="text"" name="year" size="20" maxlength="60" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>" /></p>
<p><input type="submit" name="submit" value="Update" /></p>
</form>
<?php include ('bookincludes/footer.html'); ?>
This is what If I try to change the ISBN got:
System error. We apologize for any inconvenience.
Query: UPDATE Books SET ISBN='978-1782175910' WHERE ISBN =
978-1782175919
If I tried to update the ISBN or the year but I get the message above.
How can I fix this?
The query requires that text values are wrapped in quotes like this
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = '$row[0]'";
Although I would look for a tutorial that uses parameterised and prepared queries rather than string concatenated queries to avoid SQL Injection
And any tutorial that suggests using the # error silencing prefix should tell you the author has no idea what they are doing and should be avoided like the plague.
you seem to be missing single quotes on your where clause
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = 978-1782175919
should be
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = '978-1782175919'

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?

PHP file upload into mysql

I have created a form as follows. What I'm doing is
User is selecting a client from drop down list and uploading file. When he clicks on Add button the page will redirect to Confirm.php.
The Confirm.php will show whatever the user has given the input i.e, Client name and name of the file which he has uploaded.
In Confirm.php the user is submitting the form and it should add to the database, except file upload remaining fields are adding to the database. In database, file upload field is showing empty. Please somebody solve this problem.
And I'm not getting how to access path variable from Confirm.php into Add.php.
I'm new to the php. So any help will be appreciated.
Thank you.
Home.php
<form action="Confirm.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<select class="required" name="client">
<?php
mysql_connect ("localhost","root","");
mysql_select_db ("eservice");
$select="eservice";
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
?>
<?php
$list=mysql_query("select * from client");
while($row_list=mysql_fetch_assoc($list))
{
?>
<?php $ct = $row_list['cname'];?>
<option value="<?php echo $ct; ?>"<?php if($ct==$select){ echo "selected"; } ?> > <?php echo $ct; ?></option>
<?php } ?>
</select>
</label>
<label> <span>SRN</span>
<?php
$con=mysqli_connect("localhost","root","","eservice");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="Select * from main";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rowcount++;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
<input name="srn" type="text" id="srn" size="15" readonly="readonly" maxlength="40" value="<?php echo "$rowcount"; ?>"/>
</label>
</div>
<label>
<span>File upload</span>
<input type="file" name ="filename" required>
</label>
<button id='send' type='submit'>Add</button>
<button id='clear' type='reset'>Reset</button>
</form>
And this is my cofirmation page
Confirm.php
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
dbconn.php
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("eservice",$dbhandle)
or die("Could not select newsite database");
?>
Here I'm adding the uploaded file into the phpmyadmin.
Add.php
<?php
include_once('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$client = $_POST['client']; // required
if($client !='')
{
$insQry = "Insert into `main` (client,upload) Values ('$client','$path')";
$insertQ = mysql_query($insQry);
if($insertQ!=''){
echo "<h2>Data inserted successfully...</h2>";
} else {
echo "<h2>Not added</h2>";
}
}
?>
Undefined Index means if that index is not set or empty...you have to check is it empty or not.
add condition in filename error
if ( $_FILES['filename']['error'] == 0 ){
///your uploading code
}
and for post veriable check it is isset or not, use ternary operator:-
$client =isset( $_POST['client'])?$_POST['client']:'';
Your confirm.php code should be
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
<input name ="path" type="hidden" value="<?php echo $path; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
You can get your hidden field value on add.php using $path = $_POST['path']

Categories