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....
Related
I am using local phpmyadmin as my database(MYSQL), I am doing something like this and i have no idea why this code is not updating the table in database. I am able to fetch data from database and show it on required page and place.
<?php
session_start();
require('db.php');
$id = session_id();
$query = "SELECT * from new_record where id='" . $id . "'";
$result = mysqli_query($con, $query) or die (mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Record</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="form">
<h1>Update Record</h1>
<?php
$status = "";
if (isset($_POST['new']) && $_POST['new'] == 1)
{
$id = session_id();
$name = $_POST['name'];
$age = $_POST['age'];
$submittedby = $_SESSION['username'];
$update = "UPDATE new_record SET name='" . $name . "', age='" . $age . "', submittedby='" . $submittedby . "' WHERE id='" . $id . "'";
mysqli_query($con, $update) or die(mysqli_error());
$status = "Record Updated Successfully. </br></br><a href='personal-profile.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">' . $status . '</p>';
}else {
?>
<div>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1"/>
<input name="id" type="hidden" value="<?php echo $row['id']; ?>"/>
<p><input type="text" name="name" placeholder="Enter Name" required value="<?php echo $row['name']; ?>"/></p>
<p><input type="text" name="age" placeholder="Enter Age" required value="<?php echo $row['age']; ?>"/></p>
<p><input name="submit" type="submit" value="Update"/></p>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
As mentioned in comments - take care of Injection issues.
session_id() taken into your $id does not have rows in your table. There are no rows in your table matching the MySQL Column id to the current session_id(). You will still have your form displayed with no values for name and age. When you fill and submit, it need to update an existing row which is not available in your table.
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.
I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;
Long time listener, first time caller. I'm having trouble with pulling a column called "Rep_IP" from a mysql table called "roster", turning it into an array, and then using that array to populate a dropdown in html. I've tried several suggestions listed here as well as other places and I'm not having any luck. The page shows up just fine but the dropdown has no options to select. I figured I would see if one of you could tell me what I am doing wrong here.
<html>
<body>
<form action="insert.php" method="post">
<p>Rep ID:</p>
<?php
$con = mysql_connect("localhost", "root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rep_stats", $con);
$query = "SELECT Rep_ID FROM roster";
$result = mysql_query($query) or die ("no query");
$result_array = array();
echo "$query"
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
?>
<select name="Rep_ID">
<?php
foreach($result_array as $rep)
{
echo "<option value=" . $rep['Rep_ID'] . ">" . $rep['Rep_ID'] . "</option>";
}
?>
</select>
Issues Handled: <input type="number" name="IssuesHandled">
Hours Worked: <input type="number" step="any" name="HoursWorked">
<input type="submit">
</form>
</body>
</html>
As you can see, the drop down is part of a form that is used to create an entry in a new table as well. I don't know if that makes a difference but I figured I would point it out.
Try this.
<select name="Rep_ID">
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
?>
</select>
Try this:
<?php
function select_list(){
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link)
{
echo ('Could not connect');
}
ELSE {
$query = "SELECT Rep_ID FROM roster";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
}
mysqli_close($link);
}
$begin_form =
<<< EODBEGINFORM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Insert data </title></head>
<body>
<form action="insert.php" method="post" name="form1">
<p>Rep ID:</p>
<select name="reps" form="form1">
EODBEGINFORM;
$end_form =
<<< EODENDFORM
</select><br>
Issues Handled: <input type="text" size="12" name="IssuesHandled"><br>
Hours Worked: <input type="text" size="12" name="HoursWorked"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
EODENDFORM;
echo $begin_form;
echo select_list();
echo $end_form;
?>
You will notice that I have used MYSQLI_ istead of MYSQL_ the reason is that this better for new code, see the comments above.
I debugged your code and ran I to a lot of problems.:-( The main problem was:
echo "$query" Your forgot the semicolon at the end of the line.
Good luck with you project.
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'";