Use HTML Form to Update SQL Data - php

I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)

If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.

Related

PROBLEMS Making a Search Page PHP and MYSQL

I'm facing an issue most probably due to my lack of experience.
I'm getting the data successfully from the MYSQL DATABASE and it is successfully populating the Second DROPDOWN menu.
The problem is... when I click in "Validate" to submit and record the data in the variable it cleans the previous option selected. I'm being unable to record the selected options in variables.
<?php
$location = "";
$locationf = "";
$system = "";
$systemf = "";
$conn = mysqli_connect('localhost', 'root', 'test', 'SRSBASE')
or die('Cannot connect to db');
$result = $conn->query("select distinct SUB_ACCOUNT from SRSLOAD");
if (isset($_POST["selec"]["account"])) {
$location = $_POST["selec"]["account"];
$locationf = $location;
$locationf = sprintf('%s', $locationf);
}
echo "Location: $locationf";
$conn2 = mysqli_connect('localhost', 'root', 'test', 'SRSBASE')
or die('Cannot connect to db');
$result2 = $conn2->query("select distinct SYSTEMNAME from SRSLOAD where SUB_ACCOUNT='$locationf'");
if (isset($_POST["selec"]["system"])) {
$system = $_POST["selec"]["system"];
$systemf = $system;
}
echo "System: $systemf";
$post_at = "";
$post_at_to_date = "";
$post_at_todate = "";
$queryCondition = "";
if (!empty($_POST["search"]["post_at"])) {
$post_at = $_POST["search"]["post_at"];
list($fiy, $fim, $fid) = explode("-", $post_at);
$post_at_todate = date('YY-mm-dd');
if (!empty($_POST["search"]["post_at_to_date"])) {
$post_at_to_date = $_POST["search"]["post_at_to_date"];
list($tiy, $tim, $tid) = explode("-", $_POST["search"]["post_at_to_date"]);
$post_at_todate = "$tiy-$tim-$tid";
//TESTING SELECTED TARGETS
//echo $post_at;
//echo "/";
//echo $post_at_todate;
}
//$queryCondition .= "WHERE RDATE BETWEEN '$fiy-$fim-$fid' AND '" . $post_at_todate . "'";
$queryCondition .= "WHERE RDATE BETWEEN '$post_at' AND '" . $post_at_todate . "'";
}
//$sql = "SELECT * from SRSLOAD " . $queryCondition . " ORDER BY post_at desc";
//$sql = "select * from SRSLOAD where rdate between '$post_at' AND $post_at_todate;"
$sql = sprintf("SELECT * FROM SRSLOAD WHERE RDATE BETWEEN '%s' AND '%s' AND SYSTEMNAME='%s' AND SUB_ACCOUNT='%s'", $post_at, $post_at_todate, $systemf, $locationf);
$result3 = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Storage Report System - Search</title>
<script src="jquery-1.9.1.js"></script>
<link rel="stylesheet" href="jquery-ui-1.11.4.css">
<style>
.table-content{border-top:#CCCCCC 4px solid; width:50%;}
.table-content th {padding:5px 20px; background: #F0F0F0;vertical-align:top;}
.table-content td {padding:5px 20px; border-bottom: #F0F0F0 1px solid;vertical-align:top;}
</style>
</head>
<body>
<h2 style='font-family:arial'>Storage Report System - Search</h2>
<form name='sname' id='sname' action='' method='POST'>
<select id='select' name="selec[account]" value="<?php echo $location; ?>" >
<option value='-1'>--Select the Location--</option>
<?php
while ($row = $result->fetch_assoc()) {
unset($sub_acc);
$sub_acc = $row['SUB_ACCOUNT'];
echo '<option value="' . $sub_acc . '">' . $sub_acc . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>
<form name='sname' id='sname' action='' method='POST' >
<select id='system' name="selec[system]" value="<?php echo $system; ?>" >
<option value='-1'>--Select the System--</option>
<?php
while ($row2 = $result2->fetch_assoc()) {
unset($syst);
$syst = $row2['SYSTEMNAME'];
echo '<option value="' . $syst . '">' . $syst . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>
<div class="demo-content">
<form name="frmSearch" method="post" action="">
<p class="search_input">
<input type="text" placeholder="From Date" id="post_at" name="search[post_at]" value="<?php echo $post_at; ?>" class="input-control" />
<input type="text" placeholder="To Date" id="post_at_to_date" name="search[post_at_to_date]" style="margin-left:10px" value="<?php echo $post_at_to_date; ?>" class="input-control" />
<input type="submit" name="go" value="Search" >
</p>
<?php if (!empty($result3)) { ?>
<table class="table-content">
<thead>
<tr>
<th width="30%"><span>SYSTEM NAME</span></th>
<th width="50%"><span>DATE</span></th>
<th width="20%"><span>HSM</span></th>
</tr>
</thead>
<tbody>
<?php
while ($row3 = mysqli_fetch_array($result3)) {
?>
<tr>
<td><?php echo $row["SYSTEMNAME"]; ?></td>
<td><?php echo $row["RDATE"]; ?></td>
<td><?php echo $row["HSM_MCDS"]; ?></td>
</tr>
<?php
}
?>
<tbody>
</table>
<?php } ?>
</form>
</div>
<script src="jquery-ui-1.10.3.js"></script>
<script>
$.datepicker.setDefaults({
showOn: "button",
buttonImage: "datepicker.png",
buttonText: "Date Picker",
buttonImageOnly: true,
dateFormat: 'yy-mm-dd'
});
$(function () {
$("#post_at").datepicker();
$("#post_at_to_date").datepicker();
});
</script>
</body>
</html>
It is because you have two forms there. Every form has its own select and submit. When you click submit, only appropriate form with select is sent.
When you want to have data from both selects, you have to have both selects in one form with one submit.
Something like this code:
<form name='sname' id='sname' action='' method='POST'>
<select id='select' name="selec[account]" value="<?php echo $location; ?>" >
<option value='-1'>--Select the Location--</option>
<?php
while ($row = $result->fetch_assoc()) {
unset($sub_acc);
$sub_acc = $row['SUB_ACCOUNT'];
echo '<option value="' . $sub_acc . '">' . $sub_acc . '</option>';
}
?>
</select>
<select id='system' name="selec[system]" value="<?php echo $system; ?>" >
<option value='-1'>--Select the System--</option>
<?php
while ($row2 = $result2->fetch_assoc()) {
unset($syst);
$syst = $row2['SYSTEMNAME'];
echo '<option value="' . $syst . '">' . $syst . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>

fetch data from array is very slow while display

This is my code:
<?php
if(isset($_POST['submit']) & !empty($_POST['appid'])) {
$app = mysql_real_escape_string($_POST['appid']);
//database parameters
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
//actual data for appid's
$appsi = mysqli_query($conp, "SELECT distinct package_name FROM `user_app` where `app_id` = '$app'");
$all = array();
while($row = mysqli_fetch_assoc($appsi)) {
$all[] = $row["package_name"]; // array problem
}
foreach ($all as $value) {
$install = mysqli_query($conp, "SELECT COUNT(*) AS installs from `install` where package_name = '$value'");
$row = mysqli_fetch_assoc($install);
$data[] = '<b>' .$row["installs"] . '</b>';
$reg = mysqli_query($conp, "SELECT COUNT( DISTINCT `imei_num` ) AS reg FROM `user_app` WHERE package_name = '$value'");
$row = mysqli_fetch_assoc($reg);
$regd[] = '<b>' .$row["reg"] . '</b>';
}
}
mysqli_close($conp);
?>
<html>
<head>
<title>script</title>
</style>
</head>
<body>
<span style="text-align: center"><h1>Beta</h1></span>
<form name="query" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>Enter Application-Specific Id:</p>
<select name='appid'>
<?php
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
$getid = mysqli_query($conp, "SELECT distinct `app_id`, `appidt` from `user_app` group by `app_id`") or die('get data failed' . mysqli_error());
while(($row = mysqli_fetch_assoc($getid)) != null) {
echo "<option value = '{$row['app_id']}' selected = 'selected'";
if ($selected == $row['app_id']) {
echo "selected = 'selected'";
}
echo ">{$row['appidt']}</option>";
}
mysqli_close($conp);
?>
</select>
<p><input type="submit" name="submit" value="Go" /></p>
</form>
<div>
<p><?php echo '<br />' .'<b>'. 'Application Id : '. $app . '</b>'; ?> </p>
<hr />
<table border=2px width=100%>
<tr>
<th><b>App Packages</b></th>
<th><b>Registrations</b></th>
<th><b>Installs</b></th>
</tr>
<tr>
<td><?php echo implode("<br><br>", $all); ?></td>
<td align="center"><?php echo implode("<br><br>", $regd); ?></td>
<td align="center"><?php echo implode("<br><br>", $data); ?></td>
</tr>
</table>
<p><?php echo "$name"; ?></p>
</div>
</body>
</html>
I am fetching my all package names in an array: all[], packages might be 10 or 20 in ranges, after this i want all downloads corresponding to packages which is on another table name downloads and packages on another table app_packages.
I can't uses join because package table contain specific packages but downloads contain many number of downloads corresponding to packages.
So, i put all packages in all[] and use them in foreach loop name $value, now i get all installs per packages and i can display it via implode function. But in my frontend, when i select an appid from dropdown as you can see, it will take huge time to retrieve downloads number per packages. This is not what i want to display because it is very time taking.
Please see this problem, and if i missing something in explanation then i apologize, prompt me and i mention it.
Using query in loop is a bad idea. that is the reason you are geting slow result. it touches database on each iteration. you can do this with subquery or join as alternative way.

advice on php post operation not running

I have donation page which when the user clicks donate it posts the data to a php file named test.php I am trying this out my first trying to echo the first name and last name but this is not working ultimately I want this php page to run a MySQL query to update the total_Donation row within a database, here is my main php page first.
Database code which sits at top of file
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
$rsNames= mysql_fetch_assoc($names_query);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$donation = mysql_real_escape_string($_GET['donation']);
$fname = mysql_real_escape_string($_GET['first_Name']);
$lname = mysql_real_escape_string($_GET['last_Name']);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname}'";
}
mysql_close($con);
?>
Here is my form section of html
form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select>
<?php do{?>
<option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
<?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation"/></td></tr>
<tr><td><input id="submit" type="submit" value="DONATE"/></td></tr>
</table>
</form>
the option gets all the first names and last names fine when the user hits donate I want it to run the $donation_sql but all i get are errors saying unidentified index, I'm even trying the below in the test.php to simply just echo the first_Name this is giving the same error.
<?php
echo $_POST['first_Name'];
?>
Can someone please help me with this, thanks.
index.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
?>
<form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select name="name">
<?php
while($list = mysql_fetch_array($names_query))
{
?>
<option value="<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>">
<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation" /></td></tr>
<tr><td><input id="submit" type="submit" name="send" value="DONATE"/></td></tr>
</table>
</form>
test.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$names = explode(' ',$_POST['name']);
$first_name= $names[0];
$last_name= $names[1];
$donation = mysql_real_escape_string($_POST['donation']);
$fname = mysql_real_escape_string($first_name);
$lname = mysql_real_escape_string($last_name);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '" .$donation. "' WHERE first_Name = '" .$fname. "' AND last_Name = '" .$lname. "'";
echo 'DEBUG (remove after OK): <br>' .$donate_sql. '<br>';
$res = mysql_query($donate_sql);
echo 'Thanks ' .$first_name. ' ' .$last_name. '<br>';
}
mysql_close($con);
?>
That´s it!
\make sure you set name for select and you have valua attr in option tag
<select name="first_Name">
<otpion value="<?php echo $rsNames['first_Name'];?>"><?php echo $rsNames['first_Name'];?>
<?php echo $rsNames['last_Name'];?>
</option>
</select>
YOu need to give a name attribute to the select:
<select name="first_Name">
<?php while ( $rsNames= mysql_fetch_assoc($names_query)):?>
<option value="<?php echo htmlspecialchars($rsNames['first_Name']).' '.htmlspecialchars($rsNames['last_Name']);?>"> [option displayed to the user here]</option>
<?php endwhile;?>
</select>
And of course use the $_POST array, not the $_GET, since you're using the POST method.

how to update postgresql rows using php?

first I want to say that I'm a beginner in postgresql and php.. my company told me to create a database that they can view and edit on local server.. so I created the database in postgresql.. created a page that views the database:
<html>
<head>
<title>Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
//database access information
require_once("DB.php");
$host = "localhost";
$user = "admin";
$pass = "";
$db = "Project_list";
$port = "5432";
//open a connection to the database server
$connection = pg_connect("host=$host dbname=$db user=$user password=$pass port=$port");
if (!$connection)
{
die("Could not open connection to database server");
}
?>
<?php
$query = 'select * from ongoing';
$result = pg_query($query); $i = 0;
echo '<html><table bgcolor="666657" width="10" height="30" border="0" cellpadding="0" cellspacing="0"><td align="center"> <h1><font color = "#ffb200"> Ongoing projects</h1>';
echo '<html><body><table border= 2 BORDERCOLOR="000000" cellpadding="1" cellspacing="0"> <tr >';
while ($i < pg_num_fields($result)) {
$fieldName =pg_field_name($result, $i);
echo '<b>'.'<td width="2" bgcolor="666657" align="center">'.'<font color = "#ffb200">'. '</b>'.'<b>'. $fieldName . '</b>'. '</td>';
$i = $i + 1; }
echo("<td><align= center><font color = #ffb200><b>Action</td>");
echo '</tr>' ;
$i = 0;
while ($row = pg_fetch_row($result)) {
echo '<tr align="center" width="1">';
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
echo '<td>' .'<font color = "#ffb200">'. $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo("<td><align= center><a href='editongoing.php?ProjectID=".$row[0]."'>Edit</a></td>");
echo '</tr>';
$i = $i + 1;
}
pg_free_result($result);
echo '</table></body></html>';
?>
<h3>
<a href="projects.php"</a>Back to projects page</a>
</h3>
<SCRIPT LANGUAGE="JavaScript">
if (window.print) {
document.write('<form> '
+ '<input type=button name=print value="Click" '
+ 'onClick="javascript:window.print()"> To Print!</form>');
}
// End -->
</script>
when you click the edit button, you will go to this page where you can edit the raw you want, this is the (edit) code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Edit Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
// attempt a connection
$connection = pg_connect("host=localhost dbname=Project_list user=admin password=");
if (!$connection) {
die("Error in connection: " . pg_last_error());
}
if ($_REQUEST['ProjectID']!=''){
$QueryStr = "Select * from ongoing where project_no='".$_REQUEST['ProjectID']."'";
$result = pg_query($connection, $QueryStr);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$row = pg_fetch_row($result);
print_r($row);
}
if ($_POST['submit']) {
// escape strings in input data
$project_no = pg_escape_string($_POST['project_no']);
$title = pg_escape_string($_POST['title']);
$duration = pg_escape_string($_POST['duration']);
$manager = pg_escape_string($_POST['manager']);
$country = pg_escape_string($_POST['country']);
$total_fee = pg_escape_string($_POST['totalfee']);
$performed = pg_escape_string($_POST['performed']);
$remaining = pg_escape_string($_POST['remaining']);
$gross_profit = pg_escape_string($_POST['gross_profit']);
$gp = pg_escape_string($_POST['gp']);
$performance_year = pg_escape_string($_POST['performance_year']);
$gp_year = pg_escape_string($_POST['gp_year']);
// execute query
$sql = "INSERT INTO ongoing (project_no, project_title, duration, manager, country, total_fee,
performed, remaining, gross_profit, gp, performance_year, gp_year)
VALUES('$project_no', '$title', '$duration', '$manager', '$country','$total_fee','$performed','$remaining',
'$gross_profit','$gp', '$performance_year','$gp_year')";
$result = pg_query($connection, $sql);
f (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($connection);
}
?>
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><b><font color = "#ffb200">
Project No.: <br> <input id="project_no" type="text" name="project_no" size="20" value=<?= $row[0] ?>>
<p>
Project Title: <br> <input id="title" type="text" name="title" value='<?= $row[1] ?>'>
<p>
Duration: <br> <input ID="duration" type="text" name="duration" value=<?= $row[2] ?>>
<p>
Project Manager: <br> <input ID="manager" type="text" name="manager" value=<?= $row[3] ?>>
<p>
Country: <br> <input ID="country" type="text" name="country" value=<?= $row[4] ?>>
<p>
Total Fee: <br> <input ID="totalfee" type="text" name="total_fee" value=<?= $row[5] ?>>
<p>
Already performed: <br> <input ID="performed" type="text" name="performed" value=<?= $row[6] ?>>
<p>
Remaining performance: <br> <input ID="remaining" type="text" name="remaining" value=<?= $row[7] ?>>
<p>
Gross Profit: <br> <input ID="gross_profit" type="text" name="gross_profit" value='<?= $row[8] ?>'>
<p>
GP%: <br> <input ID="gp" type="text" name="gp" value=<?= $row[9] ?>>
<p>
Performance actual year: <br> <input ID="performance_year" type="text" name="performance_year" value=<?= $row[10] ?>>
<p>
GP actual year: <br> <input ID="gp_year" type="text" name="gp_year" value=<?= $row[11] ?>>
<p>
<input type="submit" name="submit" value="Sumbit my table" size="30">
<P>
<a href="ongoing.php"</a>View ongoing projects</a>
<a href="editproject.php"</a>Back to editing menu</a>
</form>
</body>
</html>
My problem is, when I edit the data and click on submit my table, a new raw is inserted.. but I want it to be updated not inserted... help plz
You need to select which record (id number) you want to update, and then your query will look like
$sql = "UPDATE ongoing SET field1='value', field2='value' ... WHERE id = 'id of project you want to edit'";

Troubleshooting HTML and PHP / MySQL

Long time reader, first time poster. I am a novice PHP enthusiast, and I have a page that I have been working. Right now I have the DB connection working well and my SELECT statement is giving me the info needed. My problems are two fold (maybe more after this post; set your phasers to cringe):
At one point, I had the INSERT working, but it suddenly stopped and no amount of tweaking seems to bring it back. I have verified that the INSERT statement works in a seperate PHP file without variables.
When I did have the INSERT working, every refresh of the page would duplicate the last entry. I have tried tried several ways to clear out the $_POST array, but I think some of my experimenting lead back to problem #1.
<?php
$dbhost = "REDACTED";
$dbuser = "REDACTED";
$dbpass = "REDACTED";
$dbname = "guest_list";
// Create a database connection
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("DB's not here, man: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
// replacement for mysql_real_escape_string()
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
// Posting new data into the DB
if (isset($_POST['submit'])) {
$first = html_escape($_POST['first']);
$last = html_escape($_POST['last']);
$contact = html_escape($_POST['contact']);
$associate = html_escape($_POST['associate']);
$insert = "INSERT INTO g_list (";
$insert .= "g_fname, g_lname, g_phone, g_association) ";
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
$i_result = mysqli_query($connection, $insert);
// I have verified that the above works by setting the varialble
// in the VALUES area to strings and seeing it update
}
$query = "SELECT * ";
$query .= "FROM g_list ";
$query .= "ORDER BY g_id DESC";
$q_result = mysqli_query($connection, $query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Guest List</title>
<link href="guest.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h1>REDACTED</h1>
<h2>Guest Registry</h2>
</header>
<div class="container">
<div class="registry">
<form name="formup" id="main_form" method="post">
<fieldset>
<legend>Please enter your name into the registry</legend>
<p class="first">First Name:
<input type="text" name="first" value="" placeholder="One or more first names" size="64"></p>
<p class="last">Last Name:
<input type="text" name="last" value="" placeholder="Last name" size="64"></p>
<p class="contact">Phone Number or Email:
<input type="text" name="contact" value="" placeholder="" size="32"></p>
<p class="associate">Your relation?
<input type="text" name="associate" value="" placeholder="" size="128"></p>
<p class="submit">
<input type="submit" name="submit" title="add" value="submit" placeholder=""></p>
</fieldset>
</form>
</div>
</div>
<h3>Guest List:</h3>
<table>
<tr>
<th>Firstname(s)</th><th>Lastname</th>
<th>Phone or Email</th><th>Association</th>
</tr>
<?php while($guest = mysqli_fetch_assoc($q_result)) {
echo "<tr>" . "<td>" . $guest["g_fname"] . "</td>"
. "<td>" . $guest["g_lname"] . "</td>"
. "<td>" . $guest["g_phone"] . "</td>"
. "<td>" . $guest["g_association"] . "</td>" . "</tr>";
} ?>
</table>
<footer>
<div>Copyright <?php echo date("Y"); ?>, REDACTED, LLC.</div>
<?php
if (isset($connection)) {
mysqli_close($connection);
}
?>
</footer>
</body>
</html>
These two lines will fail:
$insert .= "VALUES ('{$first}', '{$last}', '{$contact}', '{$associate}')";
$insert .= "LIMIT 1";
Two problems here, all with the second line:
No SPACE between ) and LIMIT: )LIMIT 1 is your code;
LIMIT 1 in an INSERT is not allowed....

Categories