UPDATE: I narrowed it down, when I got rid of this tag in the header.php file it all works, can someone please explain this.
<script src="#" type="text/javascript"></script>
Hi I'm having quite an annoying issue with my php code. I am trying to update a php database, from a form, when I do this however the fields in the data base become empty after submitting. Please Help! You can view it in action here http://andcreate.com/shoelace/admin/edit1.php click on the lists on the right to edit them and see what happens.
<?php
include("header.php");
echo "<h2>Edit Posts</h2>";
echo "<div id='editNav'>";
echo "<p>Choose Post to Edit</p>";
//////////GET ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
$results = mysql_query("SELECT * FROM shoeData ");
while($row = mysql_fetch_array($results)){
$id = $row['id'];
$name = $row['name'];
$about = $row['about'];
echo "$date " . substr($name, 0, 40) . " <br/> ";
}
$thisID = $_GET['id'];
if(!isset($thisID)){
$thisID = 22;
}
//////////FINISH ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
echo "</div>";
///////IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
//has user pressed the button
$update = $_GET['update'];
if($update == "yes") {
$name = $_POST['name'];
$about = $_POST['about'];
$company = $_POST['company'];
$buy = $_POST['buy'];
//update data for this record
$sql = "UPDATE shoeData SET
name = \"$name\",
about = \"$about\",
company = \"$company\",
buy = \"$buy\"
WHERE id= $thisID";
$thisUpdate = mysql_query($sql) or die(mysql_error());
}
///////END IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
/////////// HERE WE GET THE INFO FOR ONE RECORD ONLY////////
$results = mysql_query("SELECT * FROM shoeData WHERE id=$thisID");
while($row = mysql_fetch_array($results)){
$name = $row['name'];
$about = $row['about'];
$company = $row['company'];
$buy = $row['buy'];
}
//////////////FINISH GETTING INFO FOR ONE RECORD ONLY/////////////
?>
<form name="formS" method="post" action="<?php echo $_SERVER['PHP_SELF']."?id=$thisID&update=yes";?>">
Name
<p>
<input type="text" name="name" id="name" value="<?php echo $name;?>" />
</p>
About
<p>
<input type="text" name="about" id="about" value="<?php echo $about;?>" />
</p>
Company
<p>
<input type="text" name="company" id="company" value="<?php echo $company;?>" />
</p>
Name
<p>
<input type="text" name="buy" id="buy" value="<?php echo $buy;?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" />
</p>
</form>
<p><a class="delete" href="delete.php?id=<?php echo $thisID;?>">Delete this post</a></p>
<?php
include("footer.php");
?>
You have $update = $_GET['update'];, but then right after that, you're using $_POST. A given request is either GET or POST, not both - thus whenever $_GET['update'] is set to "yes", there aren't going to be any POST vars set, and thus the update will be done with all of the values it's setting blank.
Chances are you actually meant to use either $_GET or $_POST in both places - since your updates are going through, but are blank, it sounds like you want to use $_GET (though for form submission/updates, you should probably really be using POST instead).
This may seem silly, but are you confusing $_GET and $_POST variables? You use one to check whether to enter the loop, and another to populate the string.
Also, as a minor aside, your SELECT statement towards the end of the snippet can be optimized by adding LIMIT 1 to the end of it, as presumably you're only going to be recalling one entry per id, no?
Related
Alright, so I've been working on this for two days now - my code is somewhat sloppy & jumbled but I've gone over hundreds of questions, websites, etc. etc. looking for an answer or simply an explanation I understood; unfortunately, I still have been unsuccessful in my attempts.
I am build a "Quiz" Game in PHP/HTML - the website references a database, specifically, a tabled labeled "answers" which holds the following information:
- ID: Auto-Increment
- Question: Varchar
- Answer: Varchar
- Comment: Varchar
Now, for a little information on the site - Once a user logs in, he/she can "play" the game; the game is simply an HTML form, which above it displays a random "answers table" question. The form has 4 user inputs but only requires two. Let me get into the code details and then I will ask my question:
My index.php page (which contains the game form) is currently:
<?php # index.php
session_start();
//check session first
if (!isset($_SESSION['email'])){
include ('../includes/header.php');
}else
{
session_start();
include ('../includes/header.php');
require_once ('../../mysql_connect.php');
$query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1";
$result = #mysql_query ($query);
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<div class="newGame">
<h2>Are you a Question Master?<hr /></h2>
<h3 style="color:#000">Find Out Now!</h3>
</div>
<br />
<div class="newGameContain">
<form action="gameSubmit.php" method="post" autocomplete="off">
<h2><? echo $row["Question"]."<hr />"; ?></h2>
<h3>Enter Player Answers</h3>
<p><input type="text" placeholder="Player 1" name="player1" value="<? echo $_POST['player1']; ?>" /> <input type="text" placeholder="Player 2" name="player2" value="<? echo $_POST['player2']; ?>" /></p>
<p><input type="text" placeholder="Player 3" name="player3" value="<? echo $_POST['player3']; ?>" /> <input type="text" placeholder="Player 4" name="player4" value="<? echo $_POST['player4']; ?>" /></p>
<p><input type="submit" class="submitButton" /> <input type="reset" class="resetButton" value="Reset" /> </p>
<input type="hidden" name="ID" value="<?php echo $row["ID"]; ?>" />
<input type="hidden" name"Answer" value="<?php echo $row['Answer']; ?>" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
<p></p>
</div>
<br />
<?php
} //end while statement
} //end if statement
mysql_close();
//include the footer
include ("../includes/footer.php");
}
?>
Then my gameSubmit.php page (form action) looks like this - I will only give a snapshot, not the whole thing:
<?php # index.php
session_start();
//check session first
if (!isset($_SESSION['email'])){
include ('../includes/header.php');
}else
{
session_start();
include ('../includes/header.php');
require_once ('../../mysql_connect.php');
$query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1";
$result = #mysql_query ($query);
$num = mysql_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<? if (isset($_POST['submitted'])){
$correct1Msg = "<div class='correct1Msg'><p style='color:#000;font-family:Arial, Helvetica, sans-serif;'>Player 1 entered the <span id='answerUnder'>correct answer</span>.</p></div><p></p>";
$correct2Msg = "<div class='correct2Msg'><p style='color:#000;font-family:Arial, Helvetica, sans-serif;'>Player 2 entered the <span id='answerUnder'>correct answer</span>.</p></div><p></p>";
$incorrect1Msg = "<div class='incorrect1Msg'><p style='color:#F00;font-family:Arial, Helvetica, sans-serif;'>Player 1 entered the <span id='answerUnder'>incorrect answer</span>.</p></div><p></p>";
$incorrect2Msg = "<div class='incorrect2Msg'><p style='color:#F00;font-family:Arial, Helvetica, sans-serif;'>Player 2 entered the <span id='answerUnder'>incorrect answer</span>.</p></div><p></p>";
$player1Answer = $_POST['player1'];
$player2Answer = $_POST['player2'];
$player3Answer = $_POST['player3'];
$player4Answer = $_POST['player4'];
$questionID = $row['ID'];
if ($questionID == "1" && $player1Answer != "Red"){
echo $incorrect1Msg;
}elseif ($questionID == "2" && $player1Answer != "4"){
echo $incorrect1Msg;
}else {
echo $correct1Msg;
}
if ($questionID == "1" && $player2Answer == "Red"){
echo $correct2Msg;
}elseif ($questionID == "2" && $player2Answer == "4"){
echo $correct2Msg;
}else{
echo $incorrect2Msg;
}
}
?>
<?php
} //end while statement
} //end if statement
mysql_close();
//include the footer
include ("../includes/footer.php");
}
?>
As a note, the gameSubmit.php page also has identical message and if...elseif... statements for player3Answer & player4Answer.
So my question is...
If a user is logged in and opens the index.php page, he/she is prompted with the "echo $row ["Question"]" (which is a question pulled from the MySQL database using $query = "SELECT * FROM answers ORDER BY RAND() LIMIT 1"; - The user then proceeds to enter an answer in each player's respective text input. Once the user clicks the submit button, the form redirects to gameSubmit.php - once loaded, if(isset($_POST['submitted'])){ launches and cross checks each users answer and displays the respective message.
Currently, my form redirects to gameSubmit.php, however, it doesn't reference the previous question for the correct answer - thus its sheer luck the identical answer appears when "grading" the answers.
What do I need to do/what needs to be corrected in order to achieve input validation on the form action page?
Once again, I simply want to retrieve a question at random and on submit check the inputted answers with the correct answer - I would also like my code to be able to retrieve the correct answer rather than me having to type out each answer, so that way, if a record gets added, I dont have to update the code.
Thank for your time and the help, it is much appreciated! (It's finals week and I couldn't be more stressed)
Rockmandew
Just pass a POST element from index page to gameSubmit.php with the question id.
Add a hidden element in index page like..
<input type="hidden" name="questionId" value="<?php echo $row['id']; ?>">
So, You can get the question id in pageSubmit.php using $_POST['questionId']
It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting
I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.
I want to show the selected ID data in the form and EDIT it and UPDATE in the database. I selected the data from the database and put it in the input tag but it doesn't work. Please help!
<html>
<body>
<?
$db = mysql_connect("localhost", "root","");
mysql_select_db("db_ncs",$db);
$id = $_GET['s_id'];
if($id)
{
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result);
}
?>
<form method="post" action="update.php">
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
<?
if(isset($_POST['update']))
{
$name = $_POST['s_name'];
$contact = $_POST['s_contact'];
$address = $_POST['s_address'];
$email = $_POST['s_email'];
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
$res = mysql_query($sql);
if($res)
{
echo "Upadate Successfull!";
}
else
{
echo "Sorry!";
}
}
?>
</body>
</html>
You forgot to pass the id.
Add this between the <form> tags.
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
You also need to make your methods consistent. The form submits the data via method="get" but you ask for it via $_POST. You also need to make the input names consistent with the names you ask for, by either adding or removing the "s_" in the appropriate places.
Not really an answer to your question, but i have to point you to some omissions in your code:
if $_POST['update'] is set, that doesn't mean the other variables are also set. They can be empty if user didn't enter anything in a field. You should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
In the form you have method="get" but you use $_POST in your PHP code. Try to define your form as below:
<form method="post" action="update.php">
Your SQL query should be (added quotes):
$sql = "UPDATE tbl_student
SET (s_name='$name', s_contact='$contact', s_address='$address', s_email='$email')
WHERE s_id=$id";
Try adding this after mysql_query:
$result = mysql_query($sql) or die(mysql_error());
Do not use mysql_* functions, they are no longer maintained: use PDO of MySQLi.
Doesn't he have to use the $row = mysql_fetch_assoc($result) to get the results?
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
http://php.net/manual/en/function.mysql-query.php
above is just an example.
update:
$result=mysql_query("SELECT * FROM tbl_student WHERE s_id=$id");
$row = mysql_fetch_assoc($result); // I think you have to add this line here, don't you?
?>
<form method="post" action="update.php">
<input type="hidden" name="s_id" value="<?php echo $id;?>" />
Name:<input type="Text" name="name" value="<?php echo $row['s_name'];?>" /><br>
Contact:<input type="Text" name="contact" value="<?php echo $row['s_contact'];?>" /><br>
Address:<input type="Text" name="address" value="<?php echo $row['s_address'];?>" /><br>
E-mail:<input type="Text" name="email" value="<?php echo $row['s_email'];?>" /><br>
<input type="submit" name="update" value="Update">
</form>
update 2:
when you are going to update, the method up there $id = $_GET['s_id']; is still looking for a param called 's_id' will come via HTTP GET, but it doesn't!
a quick workaround may be this,
<form method="post" action="update.php?<?php echo $id;?>">
and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
update 3:
Hmm, You still need this <input type="hidden" name="s_id" value="<?php echo $id;?>" /> and don't forget to add,
$id= $_POST['s_id']; after $email = $_POST['s_email'];!
Your form has fields like name="contact", but when you try to get the values you use $_POST['s_contact']. These need to match.
The reason you need the hidden s_id field in the form is so that you will update the same row that was edited. Your UPDATE statement contains WHERE s_id=$id, so you need to get the original id this way. It's hidden because you don't want the user to be able to change the ID when editing.
Please help, Im trying to search for mysql records using an html form to display the corresponding record for the entered primary key.
Here's my html form:
<td><input type="submit" name="Submit" value="Search"></td>
And here's the new.php form action:,
mysql_select_db("Hospital", $con);
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$_POST["fname"]}'");
while($row = mysql_fetch_array($result))
{
<input name="hnum" type="text" id="hospnum" value="<?php echo $row['HOSPNUM']; ?>" />
}
mysql_close($con);
?>
How do I get to display the hospnum in the html inputbox when I input the fname and then click the search button.
Note: This script, as-is, is vulnerable to sql-injections. The code that follows is not dealing with this, as it's out of the scope of the original question. Do not use this code as-is in a production environment.
You have a small problem jumping from PHP to HTML:
<?php
mysql_select_db("Hospital", $con) or die(mysql_error());
$fname = $_POST["fname"];
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$fname}'");
?>
<h3>Results:</h3>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<input type="text" name="hnum" value="<?php echo $row["HOSPNUM"]; ?>" />
<?php } ?>