this script displays data from a specific email address which the user enters.
the snippet of code below displays the data in a textfield at the top of the page however I want to display the data in a textfield in the body of text.
echo '<input name="login" type="text" value="' . $result['name'] . '>';
What do I change in the above code to enable me to do this.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="orders"; // Table name
$email = $_POST['textfield'];
$db = new PDO('mysql:host='.$host.
';dbname='.$db_name.
';charset=UTF-8',
$username, $password);
$stmt = $db->prepare('SELECT * FROM `orders` WHERE `email`=:email LIMIT 1');
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
?>
form:
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $result['name']?>"> //I want to display results here
</form>
if both the code exists in the same file.. this will work
<input type="text" name="name" value="<?php echo $result['name']?>">
and if you want to check if there are rows returned you can use
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
edited the code so that you know what exactly you want to do
First: Replace this code
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
just keep $result = $stmt->fetch(PDO::FETCH_ASSOC); and
if($stmt->rowCount()<=0) echo "Email not found in the database!";
Second: now in HTML section
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
As long as you don't clobber $result you can do:
<input type="text" name="name" value="<?php echo $result['name']; ?>"> //I want to display results here
echo '<input name="login" type="text" value="' . $result['name'] . '">';
Just add a double quote to the echo'd string.
It's pretty easy to accomplish. Of course make sure that the $results array is included in the session for the desired HTML page that you are working on.
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $results['name']?>"> //I want to display results here
</form>
Related
I am trying to use PHP to update an SQL table using HTML forms.
I want the user to be able to search for a VCR name and display it details in a while loop and then an update form will appear for the user to change its details in the database.
However every time i press the update button on the update form, the variables that hold the new details empty and become undefined.
<?php require('connect.php'); ?>
<?php require('headerPrivate.php'); ?>
<?php require('session.php');?>
<?php
//SEARCH PHP CODE
//THIS WORKS FINE AND ALL THE DETAILS APPEAR
if(isset($_POST["search"]))
{
//CREATE VARIABLES
$username=$_SESSION['username'];
echo "username: ".$username;
echo '<br>';
$vcrName=$_POST['name'];
echo "VCR Name: ".$vcrName;
echo '<br>';
echo '<br>';
//SELECT * FROM PRODUCT
$sql="SELECT *
FROM product
INNER JOIN user
ON product.owner_ID=user.user_ID
WHERE username='$username' AND name='$vcrName'";
echo "SQL SELECT 1: ".$sql;
echo '<br>';
echo '<br>';
//$vcrName=$_POST['name'];
$result = mysqli_query($con,$sql);
echo '<div class="row">';
echo '<div class="col-xs-6 col-md-4">';
while ($row_all = mysqli_fetch_assoc($result))
{
echo '<form method="post">';
echo "<u>Title: ".$row_all["name"].'</u>';
echo '<br>';
echo '<small>';
echo " Price: ".$row_all["price"];
echo '</small>';
echo '<br>';
echo "<p><u>Short Description:</u> ".$row_all["short_descripton"]."</p>";
echo '<br>';
echo "<p><u>Long Description:</u> ".$row_all["long_description"]."</p>";
echo '<br>';
echo '<hr>';
echo '</form>';
echo '<div>';
}
echo '</div>';
}
?>
<content>
<!--SEARCH FOR VCR NAME-->
<form class="form" method="post">
<label for="name" class="sr-only">VCR Name</label>
<input type="text" name="name" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<button name="search" type="search" class="btn btn-success btn-block">Search</button>
</form>
<?php
//This is where i run into issues. The old name in the variable $vcrName is empty and i need it for the update SQL statement.
//UPDATE PHP
if(isset($_POST["alter"]))
{
//CREATE A SESSION VARIABLE FOR THE CUSTOMER ID
$customer_ID=$_SESSION['customer_ID'];
echo "Customer ID: ".$customer_ID;
echo '<br>';
//CREATE VARIABLES
$changeTitle=$_POST["titleChange"];
$changesDescChange=$_POST["sDescChange"];
$changelDescChange=$_POST["lDescChange"];
$changepriceChange=$_POST["priceChange"];
$vcrName=$_POST['name'];
//UPDATE SQL
$sql_update="UPDATE product
SET
name='$changeTitle',
short_descripton='$changesDescChange',
long_description='$changelDescChange',
price='$changepriceChange'
WHERE
owner_ID='$customer_ID' AND name='$vcrName'";
echo "SQL Update 0: ".$sql_update;
echo '<br>';
echo '<br>';
echo "Updated Name: ".$changeTitle;
echo '<br>';
echo '<br>';
echo "SQL Update 1: ".$sql_update;
return $sql_update;
echo '<br>';
echo '<br>';
$result_update = mysqli_query($con,$sql_update);
if($result_update){
echo "Update Successful!";
}
else {
echo "Update Unsuccessful";
}
}
?>
<!--UPDATE FORM-->
<form class="form" method="post">
<label for="titleChange" class="sr-only">VCR Name</label>
<input type="text" name="titleChange" class="form-control" placeholder="VCR Name" required="" autofocus="" autocomplete="off">
<label for="sDescChange" class="sr-only">Short Description</label>
<input type="text" name="sDescChange" class="form-control" placeholder="Short Description" required="" autofocus="" autocomplete="off">
<label for="lDescChange" class="sr-only">Long Description</label>
<input type="text" name="lDescChange" class="form-control" placeholder="Long Description" required="" autofocus="" autocomplete="off">
<label for="priceChange" class="sr-only">Price</label>
<input type="text" name="priceChange" class="form-control" placeholder="Price" required="" autofocus="" autocomplete="off">
<button name="alter" type="submit">Change</button>
</form>
</content>
</body>
</html>
Your PHP code refers to a POST variable that doesn't exist:
$vcrName=$_POST['name'];
In your update form, you need to pass it as a hidden value:
<input type="hidden" name="name" value="<?=htmlspecialchars($vcrName)?>"/>
It's not clear if these are two separate PHP scripts (or if so, why they are) so you may need to put in a database call to get that value. From a user interface point of view, one is typically given the existing values when updating a record anyway. This would mean getting the data and giving each form element a value attribute.
I want to make a cofirm command page, that user after select the produse he cofirm the comand using the CONFIRM FORM, then to redirection him to the cofirm page, where he must write their dates to cofirm the command(the user dates)
So after i have a array in page cart.php
$cofirmaComanda .='<form action="cofirma_comanda.php" method="post">
<input name="prettotal" type="hidden" value="'. $pricetotal .'">
<input name="produseID" type="hidden" value="'. $item_id .'">
<input name="produseNume" type="hidden" value="'. $product_name .'">
<input name="size" type="hidden" value="'. $my_ArraySize .'">
<input name="cantitate" type="hidden" value="' . $each_item['quantity'] .'">
<input name="produse" type="hidden" value="'. $item_id .'">
<input type="submit" name="CofirmaComanda" value="cofirma_comanda"></form>';
then the cofirm page
<?php
session_start(); // Start session first thing in script
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to the MySQL database
include "storescripts/connect_to_mysql.php";
?>
<?php
$pretTotal = $_POST["prettotal"];
$PRODUSE = $_POST["produseID"];
$produseNume = $_POST["produseNume"];
$size = $_POST["size"];
$cantitate = $_POST["cantitate"];
echo "ID: ".$PRODUSE."<br>";
echo "nume produs selectat: ".$produseNume." <br>";
echo $pretTotal." preata total in LEI<br>";
echo $cantitate." cantitate<br>";
echo $size." dimensiune<br>";
// Filter Function -------------------------------------------------------------------
function filterFunction ($var) {
$var = nl2br(htmlspecialchars($var));
$var = str_replace("/", "\\\\", $var);
$var = preg_replace("~/~", "\\\\", $var);
return $var;
}
$pretTotal = filterFunction($pretTotal);
$PRODUSE = filterFunction($PRODUSE);
$produseNume = filterFunction($produseNume);
$size = filterFunction($size);
$cantitate = filterFunction($cantitate);
if(isset($_SESSION["sumbitDateClienti"])){
$nume = $_POST["nume_client"];
$comanda = 'IDprodus: '.$PRODUSE.' / produseNume: '.$produseNume.' / cantitate: '.$cantitate.' / dimensiune: '.$size.' ';
$stmt = $con->prepare("INSERT comanda (pret_comanda, comanda) VALUES (?, ?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("ss", $pretTotal, $comanda);
$stmt->execute();
if($stmt->execute()) {
echo "<strong>succes</strong> pagina a fost creata\n titlu: n<a href='admin_index_istorie.php'><strong>Inapoi la pagina de modificare istorie</strong></a>";
}
else {
echo "eroare";
}
$stmt->close();
}
else{
echo "completeaza forum pentru a finaliza comanda";
}
?>
the form on the cofirm page
<form action="" method="post">
nume: <input name="nume_client" type="text">
<input type="hidden" name="prettotal" value="<?php echo $_POST['prettotal'] ?>">
<input type="hidden" name="produseID" value="<?php echo $_POST['produseID']; ?>">
<input type="hidden" name="produseNume" value="<?php echo $_POST['produseNume']; ?>">
<input type="hidden" name="cantitate" value="<?php echo $_POST['cantitate']; ?>">
<input type="hidden" name="size" value="<?php echo $_POST['size']; ?>">
<input type="submit" name="sumbitDateClienti" value="ok">
</form>
I am stucking in this problem because if i put a name on the field is noting doing, doesnt insert the query in the database, and also doesnt give me the else return with the error
I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }
I have in the form like
<form action="sub.php" method="post">
<input type="text" name="username[]"><br>
<input type="text" name="hometown[]"><br>
<input type="text" name="country[]"><br>
<input type="submit" value="submit">
</form>
sub.php
$username = $_POST["username"];
foreach($_POST['username'] AS $ID => $Value){
echo "Checkbox with value ".$sValue." was checked!<br>";
}
I could get only one one input field i.e., username
Can we get all 3inputs to sub.php
If I understand the question
<form action="sub.php" method="post">
<input type="text" name="user[1][name]"><br>
<input type="text" name="user[1][hometown]"><br>
<input type="text" name="user[1][country]"><br>
<input type="text" name="user[2][name]"><br>
<input type="text" name="user[2][hometown]"><br>
<input type="text" name="user[2][country]"><br>
<input type="submit" value="submit">
</form>
PHP
$users = $_POST["user"];
foreach($users AS $ID => $info){
echo "user $ID ({$info['name']}) lives in {$info['hometown']}<br>"; // dollar symbol added
}
echo "all usernames: ";
$all_ids = array_keys($users);
foreach($all_ids as $current_id) {
echo $users[$current_id]['name']." ";
}
I'm not sure what your question is but there are a few issues with your html. It should be the following:
<form action="sub.php" method="post">
<input type="text" name="username"><br>
<input type="text" name="hometown"><br>
<input type="text" name="country"><br>
<input type="submit" value="submit>
</form>
I removed the brackets from the fields because brackets normally imply that you want your php code to see it as an array of values but you have single text fields.
If you want to get all of the inputs from the form you should use:
foreach($_POST AS $ID => $Value){
echo "Textbox with value ". $Value ." was used!<br>";
}
I changed it to textbox because your form doesn't have any checkboxes
try this (not elegant but should show you where its going wrong..)
$username = $_POST["username"];
foreach($_POST['username'] AS $ID => $Value){
echo "Checkbox with value ".$Value." was checked!<br>";
}
$hometown = $_POST["hometown"];
foreach($_POST['hometown'] AS $ht_ID => $ht_Value){
echo "Checkbox with value ".$ht_Value." was checked!<br>";
}
$username = $_POST["country"];
foreach($_POST['country'] AS $c_ID => $c_Value){
echo "Checkbox with value ".$c_Value." was checked!<br>";
}
If you have equal # of username,hometown,country and in correct sequence, then you can use following way
foreach($_POST['username'] AS $ID => $Value){
echo "Username ".$Value." was checked!<br>";
echo "Hometown ".$_POST['hometown'][$ID]." was checked!<br>";
echo "Country ".$_POST['country'][$ID]." was checked!<br>";
}
I am having the hardest time figuring out something that I think should be simple. I need to update multiple rows in my database with one submit button. I have it working with a submit for each row now, but I need to combine it. Here's what I'm trying. Where have I gone wrong? (I've been going off of multiple tutorials I found online and I think I have things all mixed up).
Here's the form:
<?php foreach ($teams as $team):
$id[]=$team['id'];?>
<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />
<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />
<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />
<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />
<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />
<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />
<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>
Here's the PHP to handle the UPDATE:
try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}
}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
Thanks in advance!
There are a couple of things that need fixing.
The FORM must be outside the foreach.
The '...name="name" value="...', to agree with the _POST code, should read instead:
... name="name" value="...
This way, a single POST will submit, say,
name123="Rangers"
mwins174="123"
Then you need all IDs. You can do that by issuing, in the foreach, this:
<input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />
This will result in HTML:
<input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />
and in $_POST['id'] being an array containing 123, 456 and so on.
You could also put in HTML:
<input type="text" name="name[<?php print $team['id']; ?>]" value="...
so that $_POST['name'] would be a vector with the same keys as the values of id, and therefore:
foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}
This way you have one SUBMIT, and multiple UPDATEs.
Since all your field names change for each UPDATE query, you will need to execute separate queries as you already do. I don't think you would be able to perform a single UPDATE query.
I don't understand, what's wrong with executing several update queries?