mySQL php update - php

How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}

How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");

You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.

Related

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

Saving a value from select option to database

So i am trying to insert some data in my database, unfortunatly it doesn't work as i hoped.
This is my index.php file here i made a little piece of php code to get the select options from my database(this works fine). But now i want people to select from the options in my database and store the selected option in another db table.
<?php
$query = "SELECT event_naam FROM events";
$result2 = mysqli_query($dbconn, $query);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[0]</option>";
}
?>
<form class="inschrijven" method="POST" action="includes/inscscript.php">
<select name="iselect">
<?php echo $options;?>
</select><br><br>
<span>Uw Naam: </span><input type="text" name="inaam" placeholder="Naam"><br>
<span>Leeftijd: </span><input type="number" name="leeftijd"><br>
<span>Aantal Personen:</span><input type="number" name="personen"><br>
<input type="submit" name="inschrijven" value="Inschrijven!">
</form>
I have tried this, but it doesn't do anything it also doesn't give an error.
require_once 'connectie.php'; //Connection to Database File
$sql = "INSERT INTO inschrijven (inschrijf_event, inschrijf_naam, inschrijf_leeftijd, inschrijf_personen) VALUES
('".$_POST['iselect']."','".$_POST['inaam']."','".$_POST['leeftijd']."','".$_POST['personen']."')";
if ($dbconn->query($sql) === TRUE) {
header( "Location: ../index.php" );
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $dbconn->error."');</script>";
}
$dbconn->close();
This is my inscscript.php file
I tried searching for similair qeustions but couldn't find anything like this.
$query = "SELECT event_naam FROM events";
$result=mysqli_query($con,$query)
{
// Return the number of rows in result set
while($rowcount=mysqli_num_rows($result)){
echo "<option value='".$rowcount['event_naam']."'>".$rowcount['event_naam']."</option>
}
Include this php file to your html between select opend and closing tags

update mysql record to add count when button on loop is clicked

I have a form that displays candidates with their details using a mysql while loop and below each candidate is a "vote" button which is also inside the loop. I need to add 1count to a record when their button is clicked. My problem is the buttons inside the loop has the same names so they are all affected with the update even if only one is clicked.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ename FROM election_title ORDER BY `sdate` ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$ename= $row['ename'];
?>
<p><font size= "6px" align = "center" color = "#efbf77"> <?php echo $row['ename']. "<br>";?></p>
<?php
$sql = "SELECT * FROM candidate_list T1 INNER JOIN election_title T2 ON T1.ename = T2.ename WHERE T1.ename LIKE '%$row[ename]%';";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
while($rowval = $res->fetch_assoc()) {
$id= $rowval['id'];
$image_content= $rowval['image_content'];
$ename= $rowval['ename'];
$pos= $rowval['pos'];
$fname= $rowval['fname'];
$mname= $rowval['mname'];
$lname= $rowval['lname'];
?>
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode( $rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
<form action="castvote.php" method="post">
<INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>">
</div>
<?php
}
} else {
echo "No candidate(s) listed.";
}
?>
<?php
}
} else {
echo "0 results";
}
?>
And this is my query.
<html>
<head>
<title>NSDCI Voting System</title>
<link rel="stylesheet" href="css/style.css">
</head>
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'voting_system';
$fname = $_POST['fname'];
$con = mysqli_connect($host, $user, $pass, $db);
if($con)
{
$sql = "UPDATE candidate_list SET votes = votes +1 WHERE fname = $fname";
$query = mysqli_query($con, $sql);
if($query)
echo 'data inserted succesfully';
}
echo 'connected succesfully to the db!';
?>
How can i query a WHERE clause that matches my button name. Thanks in advance
One way would be to assign, to each button, a dataset attribute - such as data-id=$rowval['id'] and use javascript to read that dataset value and either send an ajax request or submit the form with that value. You would not need a form for every candidate - one form should suffice and change the value of a hidden field.
Presumably fname means forename or firstname - if so then that is not a good item to use in your update statement, especially if the candidate's firstname is John for example where there a likely to be many. As each candidate in the db has his/her own ID it would make sense to use the ID for the update because that is guaranteed(?) to be unique.
<html>
<head>
<title>vote</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var form=document.forms['vote'];
var bttns=document.querySelectorAll('input.candidate');
for( var n in bttns )if( bttns[ n ].nodeType==1 )bttns[ n ].addEventListener('click',function(e){
form['id'].value=this.dataset.id;
form.submit();
}.bind(bttns[n]),false);
},false);
</script>
</head>
<body>
<form id='vote' action="castvote.php" method="post">
<input type='hidden' name='id' />
</form>
<?php
if ( $conn->connect_error )exit('unable to connect to database');
/*
not sure about the query but there should be no need to use nested queries in a loop
when a join or a selection as below should suffice.
*/
$sql="select * from `candidate_list` c
inner join `election_title` e on c.`ename` = e.`ename`
where c.`ename` in ( select distinct `ename` from `election_title` );";
$res = $conn->query( $sql );
if( $res->num_rows > 0 ) {
while( $rs = $res->fetch_object() ){
$id=$rs->id;
$pos=$rs->pos;
$image=$rs->image_content;
$ename=$rs->ename;
$fname=$rs->fname;
$mname=$rs->mname;
$lname=$rs->lname;
$pname=$rs->pname;
echo "
<div class='cand'>
<img src='data:image/jpeg;base64," . base64_encode( $image ) . "' />
<p class='bold'>
{$fname}{$mname}{$lname}
</p>{$pos}
<br/>
{$pname}
<input type='button' data-id='{$id}' class='candidate' value='Vote for {$fname}' />
</div>";
}
}
?>
</body>
</html>
Using the above methodology would mean that the PHP code that updates the db needs to be changed to use the ID ( ie: $_POST['id'] )
$sql = "UPDATE candidate_list SET votes = votes+1 WHERE id='{$_POST['id']';";
I realise the code is vulnerable to sql injection - prepared statements is the way forward.
One thing I noticed after posting my answer was the base64_encode( $image ) line - if this is coming from the db, as it is, then I guess that would be the path to the image rather than RAW data? If that is the case the line ought to read base64_encode( file_get_contents( $image ) )
In response to the valid comment about insecure code - how the use of prepared statements could be used to mitigate against sql inection.
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<title>NSDCI Voting System</title>
<link rel='stylesheet' href='css/style.css'>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['id'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'voting_system';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
$sql='update `candidate_list` set `votes` = `votes`+1 where `id`=?';
$stmt=$db->prepare( $sql );
if( $stmt && $id ){
$stmt->bind_param( 's', $id );
$result=$stmt->execute();
echo $result ? 'data inserted succesfully' : 'oops';
}
}
?>
</body>
</html>
I am changing the below part of your code.
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
<form action="castvote.php" method="post">
<INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>">
</div>
Try considering the idea of not using form. You can use a hyperlink with the action script. Pass the AutoIncrement value from the target table of the selected candidate via the URL. After this, fetch the value in your action script using $_GET and do the update. To ensure that the action script is not accessed directly, add the isset($_GET) validation. Below is the code.
<div class = "cand">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
//I am changing your code here.
Vote <php echo $fname; ?>
</div>
Now in your action script, use the below code.
if (isset($_GET['id'])) {
$id_to_update = $_GET['id'];
//Have your PHP update code here with the target id.
}
Hope this helps.

SQL query returning false in PHP

I am trying to perform this query in PHP however it keeps returning false. I have tried the query in phpMyAdmin and it works fine so if anyone can spot what is wrong that would be great. Also how can I get some better error messages for problems like this so I can try and solve the problem?
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
return 1;
}
I have already used $stmt = $conn->prepare(query); for a different query in the same block of PHP code which runs fine so I don't know if that is anything to do with it.
Thanks in advance :)
EDIT: I was asked where I bind the '?' used in the query. $stmt->bind_param('i', $albumArtID); I didn't include it in the question originally because the echo in the if statement runs so I presumed it was encountering an error before the bind_param.
EDIT 2: As requested here is the code used to make the connection:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'psyjb6';
$conn = new mysqli('localhost', 'root', '', 'psyjb6');
if ($conn->connect_errno)
echo"<p>failed to connect to database</p>";
?>
EDIT 3: Here is the entire main section of code from that page, hopefully we can figure this out:
<form name="editAlbum" method="get" onsubmit="return validateForm(this)">
<div class="row">
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'connection.php';
if(isset($_GET["album"]))
{
/* If album was passed in the URL then get current values
for that album */
$stmt = $conn->prepare("SELECT cd.artID, artName, cdTitle, cdPrice, cdGenre, cdTracks FROM cd INNER JOIN artist ON (cd.artID = artist.artID AND cdID = ?);");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$albumID = htmlspecialchars($_GET["album"]);
$stmt->bind_param('i', $albumID);
$stmt->execute();
$stmt->bind_result($albumArtID, $albumArtName, $albumTitle,
$albumPrice, $albumGenre, $numTracks);
$stmt->fetch();
/* Create input fields */
// Album Title
echo "<div class=\"row horizontal-center\">" .
"<input type=\"text\" value=\"" . htmlspecialchars($albumTitle) . "\" name=\"albumTitle\"/>" .
"</div>";
// Artist Name
echo "<div class=\"row horizontal-center\">" .
"<h6>By Artist:</h6>" .
"</div>";
echo "<div class=\"row horizontal-center\">" .
"<select name=\"artID\">";
/* Create option for current artist so it will be first in list */
echo "<option value=\"$albumArtID\">$albumArtName</option>\n";
/* Generate list of artists except artist currently associated with the album */
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?");
if($stmt === false)
{
echo $conn->error;
echo "hi";
exit;
}
$stmt->bind_param('i', $albumArtID);
$stmt->execute();
$stmt->bind_result($artID, $artName);
/* Check if no artists were found */
if(!$stmt->fetch())
echo "<p>No artists were found!</p>";
else
{
/* Create options for artists that were found */
do
{
echo "<option value=\"$artID\">$artName</option>\n";
}while($stmt->fetch());
}
echo "</select>" .
"</div>";
// Album Price
echo "<div class=\"row horizontal-center\">" .
"<input type=\"number\" step=\"0.01\" value=\"" . htmlspecialchars($albumPrice) . "\" name=\"albumPrice\"/>" .
"</div>";
// Album Genre
echo "<div class=\"row horizontal-center\">" .
"<input type=\"text\" value=\"" . htmlspecialchars($albumGenre) . "\" name=\"albumGenre\"/>" .
"</div>";
// Number of Tracks
echo "<div class=\"row horizontal-center\">" .
"<input type=\"number\" value=\"" . htmlspecialchars($numTracks) . "\" name=\"numTracks\"\n/>" .
"</div>";
// Delete checkbox
echo "<div class=\"row\">" .
"<div class=\"col-2\">" .
"<h6>Delete:</h6>" .
"</div>" .
"<div class=\"col-1\">" .
"<input type=\"checkbox\" name=\"delete\" value=\"Delete\"/>" .
"</div>" .
"</div>";
/* Create hidden field to submit the album ID with the form */
echo "<input type=\"hidden\" value=\"" . htmlspecialchars($albumID) . "\" name=\"albumID\"\n/>";
}
else
{
/* Send browser back to artists page if they somehow accessed
the edit page without going through the "Edit" link next
to an artist in the table. This would be the artName variable
would not be sent via the URL.*/
header("Location: artists.php");
}
?>
</div>
<div class="row">
<div class="col-2">
<h6>Delete:</h6>
</div>
<div class="col-1">
<input type="checkbox" name="delete" value="Delete"/>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Update"/>
</div>
<!-- PHP to edit album data -->
<?php
include 'connection.php';
if(isset($_GET["delete"]))
{
$albumID = $_GET["albumID"];
/* Create DELETE query */
$stmt = $conn->prepare("DELETE FROM cd WHERE cdID = ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$stmt->bind_param('i', $albumID);
$stmt->execute();
}
else if(isset($_GET["albumTitle"]) && isset($_GET["albumGenre"])
&& isset($_GET["albumPrice"]) && isset($_GET["numTracks"]))
{
$albumTitle = htmlspecialchars($_GET["albumTitle"]);
$artID = htmlspecialchars($_GET["artID"]);
$albumGenre = htmlspecialchars($_GET["albumGenre"]);
$albumPrice = htmlspecialchars($_GET["albumPrice"]);
$numTracks = htmlspecialchars($_GET["numTracks"]);
/* Create INSERT query */
$stmt = $conn->prepare("UPDATE cd SET (cdTitle = ?, artID = ?,
cdGenre = ?, cdPrice = ?, cdTracks = ?) WHERE cdID = ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$stmt->bind_param('sisdi', $albumTitle, $artID, $albumGenre,
$albumPrice, $numTracks);
$stmt->execute();
}
?>
</form>
If you are using parameterized queries, then you have to pass the value for the parameter when you execute the prepared query.
You also have to execute the prepared query. The prepare just passes the query to the database for compilation and optimisation, it does not actually execute the query.
Also if you get an error in these database access statement, there are functions/methods you should use to show the the actuall error message which are a lot more useful than outputting something you make up yourself like echo "Error creating SQL statement";
Also the ; is not necessary.
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?");
if ( $stmt === false ){
echo $conn->error;
exit;
}
$stmt->bindParam('i', $some_variable)
$result = $stmt->execute();
if ( $result === false ) {
echo $stmt->error;
exit;
}
Close first connection using mysqli_close($conn); after first query is finished then open a new connection with include 'connection.php'; before the second query. Credit to #Chay22

Retrieve data from database into a html form

I have code to retrieve data from a database into a form but it doesnt seem to be working. The code below is my attempt but it doesnt work. Currently, when I click the submit button 'retrieve rose' it does nothing...
//if we have no errors, do the SQL
if (!$errors) {
$latin_name = $_POST['latin_name'];
$stmt = $conn2->prepare("SELECT common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type,
price, stock_level, fragrance, ultimate_height FROM rosename WHERE latin_name = ?");
$stmt->bind_param('ssssssssdiss', $latin_name);
if ($result = $stmt->get_result()) {
/* fetch associative array */
echo "<form><input type='text' value='" . $row["common_name"] . "' name='latin_name' />";
echo "<input type='text' value='" . $row["variety_name"] . "' name='soil_type' /></form>";
} // i no I need to add more here...
exit;
}
//put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
require_once('footer.php');
exit;
}
//if we do have errors, show the error message
else {
echo "<p>".$error_msg."</p>";
}}
?>
And here is my form:
<h1>Update Rose Item</h1>
<ul class='register'>
<li>
<form action="updaterose.php" id="updaterose" method="post">
<fieldset id="register">
<label>Latin Name:<span class="small">Enter a Latin Name</span></label><input name='latin_name' id='latin_name' type='text' value="<?=(isset($_POST['latin_name'])? $_POST['latin_name']:"");?>" />
<input type="submit" value="Retrieve Rose" name='retrieverose' /></br></br></br>
</form>
Code requested by mariogl
//connect to database
$conn2 = DB2();
require_once('header_admin.php');
if (isset($_POST['updaterose']))
{
//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";
Your problem is the first condition, you're asking for a variable named "updaterose", that doesn't exist. Try this:
if (isset($_POST['retrieverose']))
{
//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";
//if we have no errors, do the SQL
if (!$errors) {
$latin_name = $_POST['latin_name'];
$stmt = $conn2->prepare("SELECT common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type, price, stock_level, fragrance, ultimate_height FROM rosename WHERE latin_name = ?");
$stmt->bind_param('s', $latin_name);
$stmt->execute();
if ($result = $stmt->get_result()) {
/* fetch associative array */
echo "<form><input type='text' value='" . $result["common_name"] . "' name='common_name' />";
echo "<input type='text' value='" . $result["variety_name"] . "' name='variety_name' /></form>";
// i no I need to add more here..
exit;
}
//put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
require_once('footer.php');
exit;
}
//if we do have errors, show the error message
else {
echo "<p>".$error_msg."</p>";
}}
}
Corrections on brackets and bind_param().

Categories