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().
Related
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
My UPDATE query is failing although the syntax looks fine to me (I have another update query that works fine on the same page).
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
$id = $_GET['id'];
if (isset($_POST['submit'])){
$b = mysql_real_escape_string(trim($_POST['body']));
//**You have an error in your SQL syntax;** --> ?
mysql_query ("UPDATE body SET body= $b WHERE id = $id") or die (mysql_error() );
// $b is fine
echo "$b";
}
How the HTML review forms are rendered..
// Puts SQL Data into an array
$q = mysql_query("SELECT * FROM vote") or die (mysql_error());
// Now we loop through the database
echo "<br />";
while ($ratings = mysql_fetch_array($q))
{
//This outputs the doctors's name
echo "Doctor's name:" . $ratings['doctor_name'] ."<br />";
//This outputs a textarea for the user to submit comments
echo "<b>Your Experience: </b>";
echo "<form method='post' action='review_doctors.php'>
<textarea name='body'></textarea>
<input type='submit' name='submit' value='Send' id='submit'/>
</form>
";
echo "<br />";
echo "<p> </p>";
}
Why am I getting a SQL syntax error whenever a comment is submitted?
So, you're setting $id from the $_GET array which will probably not be set on submission of a form via post.
The update query you're running is inside a check for a POST (checking to see if $_POST['submit'] is set).
You probably want to send the value for the $id in the post body and pull it from the post array.
I fixed it to this:
// If submitted
if (isset($_POST['id'])){
//Capture what was typed in textarea
$b = mysql_real_escape_string(trim($_POST['body']));
$id = $_POST['id'];
mysql_query ("UPDATE vote SET body = '$b' WHERE id = $id") or die (mysql_error() );
// $b and $id are still fine
echo "$b";
echo "$id";
}
Also fixed the hidden input value:
while ($ratings = mysql_fetch_array($q))
{
//This outputs the doctors's name
echo "Doctor's name:" . $ratings['doctor_name'] ."<br />";
$id = $_POST['id'];
//This outputs a textarea for the user to submit comments
echo "<b>Your Experience: </b>";
echo "<form method='post' action='review_doctors.php'>
<textarea name='body'></textarea>
<input type='submit' name='submit' value='Send'/>
<input type='hidden' name='id' value='$ratings[id]' />
</form>
";
echo "<br />";
I'm learning PHP and I am now on creating an all in one web form that adds a new subscriber record to the subscribers table in the newsletter database. This is my first time on this site, so excuse any n00biness.
The comments explain the portion of code which determines whether the form will be processed. I'm not sure if it needs to go inside the if..else statement that validates the submitted form data, or if it goes after the validation in its own if..else.
When I put it inside the validation, the html form shows, but when I hit submit, all the info refreshes and nothing happens.
When I put it after the validation, the html form does not show, I get an error saying undefined variable: FormErrorCount. It then tells gives me the id number I'm supposed to get, but I did not enter a name or email (due to the html form not showing) and that is left blank.
There is an include file, but that is just fine.
I'm sure once this gets figured out, I will have the feeling to want to slap myself, but I have been staring at the screen way too long. Thank you
<?php
$ShowForm = FALSE;
$SubscriberName = "";
$SubscriberEmail = "";
if (isset($_POST['submit'])) {
$FormErrorCount = 0;
if (isset($_POST['SubName'])) {
$SubscriberName = stripslashes($_POST['SubName']);
$SubscriberName = trim($SubscriberName);
if (strlen($SubscriberName) == 0) {
echo "<p>You must include your name</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubName' field)!</p>\n";
++$FormErrorCount;
}
if (isset($_POST['SubEmail'])) {
$SubscriberEmail = stripslashes($_POST['SubEmail']);
$SubscriberEmail = trim($SubscriberEmail);
if (strlen($SubscriberEmail == 0)) {
echo "<p>You must include your email address!</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubEmail' field)!</p>\n";
++$FormErrorCount;
}
//CODE BELOW IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName " .
" (name, email, subscribe_date) " .
" VALUES('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
//CODE ABOVE IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
}else{
$ShowForm = TRUE;
}
/* CODE BELOW IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE, BUT NOT SURE WHERE IT BELONGS
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName (name, email, subscribe_date) " .
"VALUES ('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
*/CODE ABOVE IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE SECTION, BUT NOT SURE WHERE IT BELONGS
//HTML PORTION
if ($ShowForm) {
?>
<form action = "NewsletterSubscribe.php" method = "POST">
<p><strong>Your Name: </strong>
<input type = "text" name = "SubName" value = "<?php echo $SubscriberName; ?>" /></p>
<p><strong>Your Email Address: </strong>
<input type = "text" name = "SubEmail" value = "<?php echo $SubscriberEmail; ?>" /></p>
<p><input type = "Submit" name = "Submit" value = "Submit" /></p>
</form>
<?php
}
?>
Your code, ignoring for now the ShowForm part at the end, is structured like this:
if this is a submit {
validate the form data
if there are no errors {
save the form data
}
}
This looks reasonable. Maybe your form isn't being submitted as a POST? Check your <form action> and also use Firebug to make sure the form data is being submitted.
If you were to move the error check, you would have:
if this is a submit {
validate the form data
}
if there are no errors {
save the form data
}
And that's wrong because if the form were not being submitted, then you'd have no errors (hence the "undefined variable" error) and then it would attempt to save the nonexistent form data.
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.
If i click on my search field and submit it without entering any text all the data in my database is returned. How is this stopped so nothing happens?
Check out the site:
weezy.co.uk/newresults.php
Thanks!
James
<?php
$conn = mysql_connect("cust-mysql-123-02", "uwee_641290_0001", "La0%-Mr4");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
you should check if it's empty before making a query:
if(empty($_POST['searchterm'])){
//don't search and show an error message
}else{
//proceed as normal, do the query
}
otherwise you might end up making a query like:
WHERE name LIKE('%%')
which is really expensive and returns all your database rows
Best way to do this (imo) is to have a simple javascript checking if the input is blank or not.
It is always wise to do some front end using javascript/Jquery. form validation where you are prompting users to input something.
Once you are done you may also check on the back end using the following:
if(isset($_POST['searchterm'])){
// search for the results.
}else{
// do nothing or show proper message
}
I think the best way would be to disable the submit button on the client side whenever your search box is empty.
You could do something like:
$(document).ready(function()
{
$('#searchBox').keyup(function()
{
if($(this).val() == '')
{
$('#searchButton').attr('disabled', true);
}
else
{
$('#searchButton').removeAttr('disabled');
}
});
});
where your html is like:
<input type='text' id="searchBox" />
<input type='button' id='searchButton' value='search' disabled/>
Make sure to validate on the server side as Nicola has indicated.
I was facing some problems in the above code. So the following improved version of the above code works just fine:
<form action="searchengine.php" method="POST">
<input type="text" id = "searchbox" name="searchterm" placeholder="Search here">
<input type="submit" id = "searchbutton" value="Search" style="display:none;">
</center>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#searchbox').keyup(function()
{
if($(this).val() == '')
{
$('#searchbutton').hide();
}
else
{
$('#searchbutton').show();
}
});
});
</script>