I am trying to retrieve a value from database and put it in a textbox.
I tried:
<input type="text" name="Balance" value="<?php $Balance= $_GET["Balance"]; ?>" readonly = "true" />
and:
<input type="text" name="Balance" value="<?php echo $Balance; ?>" readonly = "true" />
But I am getting an error saying that Balance is undefined.
The php script is located in another page (connect.php) and I already put the
<form method="post" action="connect.php" >
What else should I do?
TIA
First of all your form method is POST, so:
... $Balance= $_POST["Balance"]; ...
I think you dont know anything about what you are currently doing.
$_GET is not used to fetch something from a Database, it is used to pass and fetch parameters via URL. For accessing a Database, you need mysqli or PDO. Look for some tutorials.
Example for the code you need:
$sql = "SELECT balance FROM mytable";
$result = $db->Execute($sql);
echo "<input type='text' name='Balance' value='" . $result . "' readonly/>"
Just for you to get an idea:
mysql_connect('127.0.0.1', 'root', '')
and mysql_select_db('accounting')
and ($res = mysql_query("SELECT `id`,`balance` FROM `accounts`"))
and ($row = mysql_fetch_object($res));
HTML:
<input type="text" name="Balance" value="<?= $row->balance ?>" >
It won't work on your computer, because I don't know the tables you're using and other things I need to know, and anyway, do a search, this topic probably has been covered a million times in the last 10-15 years since PHP exists, long before Stack Overflow existed.
PS: That's one of the oldest ways of doing it. There are other ways, like PDO, but I use the "old" way and am happy with it.
Related
there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.
I am trying to pass a value that I have received from my database to another php page to use within another SQL statement.
I have tried using sessions and also passing using the $_POST method on the other page but have had no luck.
Here is a snippet of my code looping through to display all records:
while($row = mysqli_fetch_array($sql)){
echo '<td>
<img src='.'"'.$row['image'].'"'.'><br/>
<form method="post" action="edit-record.php">
<input type="text" name="imgID" value='.'"'.$row['id'].'"'.'>
<input type="submit" value="Edit" id="edit_btn" class="admin_btn"></form>
</td>';
}
The value that I need is the ID for each specific image - $row['id'].
When the user clicks the EDIT button, they should be redirected to another page which displays only the specific record. This is why I need the ID received passed to the next page to insert into a query statement.
I hope this made sense and any help will be greatly appreciated.
UPDATE: Thanks for all of your help. I solved the problem by playing around with a few of your suggestions to pass the id via GET in the action of the form.
<form method="post" action="edit-record.php?id='. $row['id'].'">
No idea why that hadn't occurred to me! Thanks again.
while($row = mysqli_fetch_array($sql)){
echo '<td>
<img src="'.$row['image'].'"><br/>
<form method="post" action="edit-record.php">
<input type="text" name="imgID" value="'.$row['id'].'">
<input type="submit" value="Edit" id="edit_btn" class="admin_btn">
</form>
</td>';
}
in edit-record.php...
<?php
echo $_POST['imgID'];
?>
There is no reason your code technically wouldn't work but instead you could just eliminate the form and use a simple link...
while($row = mysqli_fetch_array($sql)){
echo '<td>
<img src="'.$row['image'].'"><br/>
edit
</td>';
}
and in edit-record.php...
<?php
echo $_GET['id'];
?>
4 Ways to do this...
1) Use a cookie
2) Use a session (which by default uses a cookie but in a different way)
3) Use cURL
4) add it to the GET parameters... ie. somepage.com/page.php?id=1
Strange concatenation
<input type="text" name="imgID" value="'.$row['id'].'">
Sure you select id on the mysql query???
If you make
echo $_POST['imgID'];
what is the result???
You can pass the id via get in the action form:
<form method="post" action="edit-record.php?id='. $row['id'].' ">
On the other page you recive the form in $_POST and the id in $_GET['id']
~Aha, I think the problem is your quotes. Single quotes don't allow variables to be interpreted.~
Nevermind, thats not your problem, but I already wrote it out, so I'll leave it. Look how much cleaner those quotes are :)
Switch up your quotes like so:
echo "<td>
<img src='{$row['image']}'><br/>
<form method='post' action='edit-record.php'>
<input type='text' name='imgID' value='{$row['id']'}'>
<input type='submit' value='Edit' id='edit_btn' class='admin_btn'></form>
</td>";
Need curly braces around array element (e.g {$row['id']})
I have a question in regards to the GET function. I currently have a form with a get action. I am accessing that data in another page with the get function. Unfortunately, I have been getting an "error: undefined index" on every one of my values. After reading up on similar problems, I tried using isset (as seen below) and it gets rid of the error, but I am not sure that my data is stored in the variables at all because if I echo the 4 variables, nothing shows up. Could someone give me a push in the right direction?
Data from form:
while($row = mysql_fetch_array($result)) {
echo "<div class=\"addform\"><form method='GET' action=\"update.php\">\n";
echo " <input type=\"text\" value=\"".$row['tfid']."\" name=\"tfid\">\n";
echo " <input type=\"text\" name=\"fname\" value=\"".$row['fname']."\"/>\n";
echo " <input type=\"text\" name=\"lname\" value=\"".$row['lname']."\"/>\n";
echo " <input type=\"text\" name=\"hca\" value=\"".$row['hca']."\"/>\n";
echo " <input type=\"text\" name=\"file\" value=\"".$row['file']."\"/>\n";
echo " <input type=\"image\" src=\"images/update.png\" alt=\"Update Row\" class=\"update\" title=\"Update Row\">\n";
echo "<img title='Delete Row' alt=\"Delete\" class='del' src='images/delete.png'/></form></div>\n";
}
echo "</table><br />\n";
and the code for retrieval:
$tfid= isset($_GET["tfid"]) ? $_GET["tfid"] : NULL;
$fname = isset($_GET["fname"]) ? $_GET["fname"] : NULL;
$lname = isset($_GET["lname"]) ? $_GET["lname"] : NULL;
$hca = isset($_GET["hca"]) ? $_GET["hca"] : NULL;
echo $tfid;
echo $fname;
echo $lname;
echo $hca;
After your edit:
After you posted your form code, I noticed the problem may be that the values of your inputs may be empty, as the syntax looks more or less correct. Double check the values via view-source to ensure their validity.
Before your edit:
The errors are ocurring because the variable in fact is not set. Make sure your form looks like this:
<form action="yourpage.php">
<input name="fname" type="text" />
<input name="lname" type="text" />
<input name="hca" type="text" />
<input name="tfid" type="text" />
</form>
As shown above, the _GET variables are looking for the name attribute. A common mistake among beginners (everyone has been guilty of this at one time or another) is the use of id in place of name. id is used for selector purposes whereas name is often used to retrieve values on the server side.
Something to keep in mind....
As #George Cummins mentioned, you should also be aware that $_GET parameters are passed through the URL like so:
http://yoururl.com?var1=data1&var2=data2
In some cases, you may not want the user to see all of the data being sent through your form, so in this case you would want to use $_POST which is essentially a hidden passing of the form's data. In reality, this data is not truly hidden but it certainly is more hidden than the use of $_GET.
EDIT: Mangling is fixed - primary issue appears to be the php/mysql connection
In an attempt to learn how to use a MySQL db on a webpage, I'm following a basic tutorial for connecting to a MySQL instance via PHP (all managed through WAMP2)
The tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql/4 uses a PHP_SELF method (that I understand is now depreciated).
I've tried a few other suggestions that I've found doted around, but I can't find resolution to the following error I see in the apache log:
(20024)The given path is misformatted or contained invalid characters: Cannot map POST /%3C$SEARCH.PHP%3E HTTP/1.1 to file, referer: http://localhost/search.php
This error prevents the HTML page from being returned, and I get a 403 error in my browser
It appears that this line of HTML/PHP is the culprit:
<form name="search" method="post" action="<?=$PHP_SELF?>">
I have seen suggestions that say to either turn on short_open_tag (a bad idea according to some), change the
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
I can't get any of these methods to work, and wondered if anyone could let me know what dumb thing I've missed this time...
The whole php file I am using is:
<?php
// // This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
include("dbinfo.php");
mysql_connect($host,$username,$password);
mysql_select_db("database") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM main WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['Item1'];
echo " ";
echo $result['Item2'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="item1">Item1</option>
<Option VALUE="item2">Item2</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
Avoid shortags, they are out of date, make sure to be using:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What does the form's html look like when you load the page?
EDIT:
After reviewing my answer I'd like to rephrase it a bit, as they are not "out of date" per say, but they generally do cause problems (for those that don't know how to set up php fully), so for beginners I'd suggest avoiding them.
I'm sure this is probably bad design, but I've always just hard-coded the script name in cases like that (so, just action="search.php").
The $_SERVER['PHP_SELF'] variable contains the full path of your php script, for example:
/your_server_path/your_file_name.php
Obviously, when launched, your script can't find the file because it's looking for something like
/your_server_path/your_server_path/your_file_name.php
Try to do something like this:
<form method="post" action="<?='http://localhost'.$_SERVER['PHP_SELF']?>">
I can't set a variable from a post array.
I have a simple form with a hidden field in it:
<input name="sid" type="hidden" id="sid" value="<?=$sid?>">
This hidden field gets sent off to a second file (exec.php) where I have the following code:
$sid = $_POST['sid'];
For some reason, when trying to set $sid, it gets a NULL value. For haha's, I ran the following:
foreach($_POST as $var => $value)
{
echo $var . ' : ' . $value . "<br>";
}
This provided a correct value of 1938 for sid. I've looked at this for 3 hours and can't find what is happening. I expect something extremely stupid...any thoughts?
Here is the form on enter.php
<form name="form1" method="post" action="exec.php">
<input name="sid" type="hidden" id="sid" value="<? echo($sid); ?>">
<input name="ticket_totals" type="hidden" id="ticket_totals" value="<?=$ticket_totals?>">
<input name="emp" type="hidden" id="emp" value="<?=$emp?>">
<input name="submit" type="submit" id="submit" value="Submit">
<input type="submit" name="submit" id="submit" value="Close">
</form>
Here is the POST output on exec.php:
type : Other
ticket_totals : 0
emp : 105
sid : 1939
submit : Submit
Okay - this was poor syntax on my part but now I'm curious as to why.
I left out quotation marks - the solution is as simple as this:
$sid = $_POST["sid"]
Now it works like a champ.
Any takers on why? I'd guess there is a setting in the php.ini that requires the quotes. Strangely enough, I have other variables called from the POST array that i'm not using quotes for and they're working fine...
Use Console in FireBug to inspect the POST request to see what is the sid value that is being sent.
If the sid value in request is ok, use var_dump($_POST["sid"]); to see the results on the server.
EDIT: it's considered good PHP style to use the quotes when accessing the associative array because quote-less keys are indistinguishable from constants:
define('myVar',3);
echo $array[myVar]; // retrieves $array[3], not $array['myVar'];
Try to echo the $sid instead of the <?=:
// Change that
<input name="sid" type="hidden" id="sid" value="<?=$sid?>">
// With that
<input name="sid" type="hidden" id="sid" value="<?php echo $sid; ?>">
also for the test time try to change the input type from hidden to text in order to be 100% sure the $sid contains a value.
Using quotes for associative array keys is mandatory, and while it may work without them, it's incorrect and erratic behavior is expected.
I had this same problem, trying to use $_POST[sid] as a variable. I'm am thinking that "sid" is a reserved or restricted variable name, because I changed my variable to $_POST[snid] and it worked just fine. This was my code
$sid = $_POST[sid];
$recipient = "($sid) ($_POST[sid])";
if ($_POST[sid] > 0)
{
$recipient = "It Worked";
}
print $recipient;
When I posted "&sid=15", the result was:
() (15)
Unbelievable. Impossible, right? All I did was change from using "sid" as the index to "snid", and it worked no problem.
So, don't ever use $_POST[sid].