I'm trying to do something simple to learn how to do a query and then put the answer into a box. I have a HTML file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="results.php" method="post">Search: <input name="term" type="text" /><br />
<input name="submit" value="Submit" type="submit" />
<p>Answer: <input name="answer" type="text" /></p>
</form>
</body>
</html>
And the php code is:
<?php
$hostname = 'host.com';
$username = 'ratetable';
$password = 'mypassword';
$term = (int) $_GET['term'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
//echo 'Connected to database<br />';
foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $term . ' ORDER BY mileage DESC LIMIT 1') as $row) {
echo "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
So I'm trying to put ratepermile, a field in the database, into the 'answer' text box. What I get is the screen clears, but no form and no result, even after I comment out the 'connected to database' echo line and use something that I know exists in the database.
How can I keep the form on screen and echo to the text box?
Thanks for looking.
Your form is POSTing the data (method="post"), but your PHP script is looking in the $_GET aray.
You need to get the data from $_POST instead.
$term = (int) $_POST['term'];
As well as the above POST issue. If you wish to keep the form on the page and not reload the page you need to look into AJAX.
You can use $_REQUEST in order to avoid these confusions. Whether you use method="post" or method="get", you can fetch the value through this.
Related
I am doing a project and need some help please :) (full code at bottom)
The project needs to be accessed with PDO.
I need search results to appear on the same page as the search was entered.
This below doesnt seem right to me using GET instead of POST.. is this correct?
This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
How do i do that?
Also my second problem is I can not get the search form to search more than one field in a table. It just wont let me. I cant use this bit of code either
%'.$searchterm.'%
as it wont give me any feedback from the search. So i am using the
:searchterm
in
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm OR nationality ");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
Here is my full code:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_POST['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
$conn=NULL;
?>
In good practices, use POST to send params when user SEND something to the server that will change data on the server (store in db for exemple or send an email). Use GET when user RETRIEVE something from the server, to read data (query a db). So prefer GET here.
To solve your issue, simply enclose the whole code that process the research in a "if(isset($_GET['search'])){}" section as below:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_GET['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
if(isset($_GET['search'])){
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>";
}
$conn=NULL;
}
?>
This below doesnt seem right to me using GET instead of POST.. is this correct? This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
It depends on whenever you want to use GET or POST. POST is more secure, so for submitting a form I'm always using POST. In that case you can leave this code:
if(isset($_POST['search'])){
echo 'Search';
}
You do need to change the form's action type to POST:
<form action="index.php" method="post">
....
Then add the end you need to get the search value from the POST instead of GET, because we changed the action type.
$searchterm = $_POST['search'];
So i figured this out and
<!-- HTML FORM SEARCH BAR -->
<form action="index.php" method="post">
<label for="enteredterm">Enter a Weight-class or a Nationality:</label>
<input type="text" name="enteredterm">
<input type="submit" name="search">
</form>
<!-- HTML FORM SEARCH BAR -->
if(isset($_POST['search'])){
$enteredterm = $_POST['enteredterm'];
if ($enteredterm ===""){
echo "error, enter something.";
} else {
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :enteredterm OR nationality LIKE :enteredterm or lastname LIKE :enteredterm ORDER BY year");
$stmt->bindValue(':enteredterm','%'.$enteredterm.'%');
$stmt->execute();
$count= $stmt->rowCount();
echo "You entered ".$enteredterm." and returned ";
if($count <= 1){
echo $count." result.";
}else{
echo $count." results.";
}
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
I'm new to php and MySQL (working through "Head First: PHP & MySQL"). I'm trying to grab a MySQL table column name from an array and store it in the "value" for an input field of a form. For some reason, I only end up with a blank page. When I simply type in some text into the 'value', the page turns out fine.
I've checked every line of code and have narrowed it down to the input value. The database connection works and I can echo the column name in the 'while' loop, but not in the 'value'.
Here's the code:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<?php
$dbc= mysqli_connect('host', 'user', 'pass', 'elvis_store')
or die ('Error connecting to the database');
$query= "SELECT * FROM elvis_emails";
$result= mysqli_query($dbc, $query)
or die ('Error querying database');
while ($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="'$row['Id']'" name="todelete[]" />';
echo $row['Id'];
echo ' ' . $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove" />
</form>
Thank you!
instead of,
echo '<input type="checkbox" value="'$row['Id']'" name="todelete[]" />';
try like this
echo '<input type="checkbox" value="'.$row["Id"].'" name="todelete[]" />';
What is really breaking the code is the missing of proper concatenation.
It's good practice to avoid printing HTML elements with PHP echo statement. Rather, the best approach in this case would be:
<?php while ($row = mysqli_fetch_array($result)){ ?>
<input type="checkbox" value="<?=$row['Id']?>" name="todelete[]" />
<?php
...
}
mysqli_close($dbc);
?>
If by anyways you do need to print a piece of code that is relying on HTML tags and PHP variables you can make use of HEREDOC instead of using echo to print multiple lines of code.
Also, make sure that you are naming the keys to the row array the
same as your query return values.
Problem: Need to store field value when doing this query on my database. Have a couple pages that's using this same syntax but for some odd reason this isn't cooperating..
HTML
<form method="post" action="listPage.php">
<fieldset>
<legend>Pull some data</legend>
<label for="name">Name</label>
<input type="text" name="name" id="name" maxlength="255" />
<hr />
<br />
<input type="submit" value="find event" />
</fieldset>
</form>
listPage.php
<?php
//CONNECT TO DATABASE
$user="root";
$password="";
$database="db";
$connection=mysql_connect('localhost',$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
echo "NOT running...";
//STORE ALL DATA FROM PREVIOUS FORM
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
echo "running...";
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
mysql_close($connection);
?>
Check to see if the post value is set before doing anything with it. (Also, don't forget to call mysql_real_escape_string() on it).
It may not be set if this code occurs on the page when it initially loads or is refreshed after having data posted to it.
// Don't attempt any of this unless you actually have a $_POST value
if (isset($_POST['name'])) {
$name = mysql_real_escape_string($_POST['name']);
$query="SELECT event FROM events WHERE event='$name'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_numrows($result);
while ($row = mysql_fetch_array($result))
{
echo $row['event'] . " // ";
echo "<br />";
}
}
I couldn't quickly find any documentation regarding possible reserved words for POST or html form variables, so I went to
http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_form_method_post
and changed fname field to name, (clicked edit and click me button) and the POST variable was not passed or recognized.
So you might consider changing the name of your field to something other than name.
I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...