Hello I cannot figure out what is wrong with my code. Have not much experience with php yet. Can someone please tell me what am I doing wrong??
Here is my code:
<?php
include 'mysql_connect.php';
if (!isset($_POST['submit'])) {
$fuelQuery2 = sprintf("UPDATE fuel_price SET `Price` = '%s' WHERE FuelType = '%s' LIMIT 1",
mysql_real_escape_string($_POST['inputPrice']),
mysql_real_escape_string($_POST['fueltype']));
$Result = mysql_query($fuelQuery2);
if($Result){
echo 'Price has been updated!';
} else{
echo 'Failed to update price!';
}
} else{
echo 'No form submitted';
}
?>
<h1>Update Oil Price</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Oil Price:<input name="inputPrice" type="text" value=""/>
Product
<select name="fueltype">
<option value="Oil">Kero</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>
It's really simple, change
if (!isset($_POST['submit'])) {
to
if(isset($_POST['submit'])) { //Only execute the query when the form is submitted
Your original code told PHP to execute the query when the form wasn't submitted (notice that I removed the !) instead of when it was. The notices you were getting were telling you that the $_POST variables you grabbed for your query didn't exist (because the code ran before the form was submitted).
Also, do look into PDO. The mysql_ family of functions is no longer the preferred method for interacting with the database layer.
PHP
In mysql_connect.php please ensure that you call mysql_connect() and mysql_select_db().
Then you can adjust your code to the following:
<?php
include 'mysql_connect.php';
if ('POST' == $_SERVER['REQUEST_METHOD'] and
isset($_POST['fuel_type']) and
isset($_POST['oil_price'])) {
$fuel_type = mysql_real_escape_string($_POST['fuel_type']);
$oil_price = mysql_real_escape_string($_POST['oil_price']);
$SQL = "UPDATE `fuel_price`
SET `Price` = '$oil_price'
WHERE `FuelType` = '$fuel_type'";
if(mysql_query($SQL)) {
echo 'Price updated.';
} else {
echo 'Failed to update.';
}
}
?>
HTML Form
You don't need PHP_SELF in the action and you can just leave it blank to submit onto the same page.
<form action="" method="post">
<label for="oil_price">Oil Price</label>
<input name="oil_price" id="oil_price" type="text" value="" />
<label for="fuel_type">Product</label>
<select name="fuel_type" id="fuel_type">
<option value="Oil">Kerosene</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>
Related
I'm trying to insert data into a mysql database using standard sql through form.
my code is as follows:
<?php
$name="";
$ename="";
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$er = 0;
if($name=="")
{
$er++;
$ename = "Required";
}
else if(strlen($name)<2 || strlen($name)>200)
{
$er++;
$ename = "Name must contain 3-300 characters";
}
if($er==0)
{
$cn = mysqli_connect("localhost","root","","dbuscoaching");
$sql="INSERT INTO city (name,countryId) VALUES('".strip_tags($name)."',".$country.")";
if(mysqli_query($cn,$sql))
{
print '<span class= "successMessage">Country Inserted to Database</span>';
$name="";
}
else
{
print '<span class="errorMessage">'.mysqli_error($cn).'</span>';
}
}
else
{
print '<span class="errorMessage" >You have some problems in your form</span>';
}
}
?>
<form method="post" action="">
<label>Name</label><br>
<input type="text" name="name" id="name" value="<?php print $name; ?>">
<span class="error" id="ename"><?php print $ename; ?></span>
<br>
<label>Country</label><br>
<select name="country" id="country">
<option value="0">Select</option>
<?php
$cn= mysqli_connect("localhost","root","","dbuscoaching");
$sql="select id, name from country";
$table=mysqli_query($cn,$sql);
while ($row= mysqli_fetch_assoc($table))
{
print '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
When running in browser i'm getting this error message:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ')' at line 1
but in cli php the code runs with no error as shown bellow:
<form method="post" action="">
<label>Name</label><br>
<input type="text" name="name" id="name" value="">
<span class="error" id="ename"></span>
<br />
<label>Country</label><br>
<select name="country" id="country">
<option value="0">Select</option>
<option value="1">Bangladesh</option><option value="2">USA</option><option value="3">India</option><option value="4">Bhutan</option><option value="5">Maldives</option><option value="6">Nepal</option><option value="7">UK</option><option value="8">Australlia</option><option value="9"></option><option value="10">Japan</option><option value="11">Iran</option> </select>
<input type="submit" name="submit" value="Submit">
</form>
Process finished with exit code 0
though i'm following what my instructor told i'm getting this error.
can you please tell me what's the problem?
You do not assign any value to the $country variable, hence the actual sql statement looks like sg like as follows (this is why you should print out the actual sql statement, the error would be obvious):
INSERT INTO city (name,countryId) VALUES('whatever you typed in as name',)
Since there is nothing ahead of the closing parentheses, MySQL reports a syntax error. You need to assign value to $country variable:
$country=$_POST['country'];
However, pls try to avoid creating a query string through simple string concatenation. Use prepared statements with parameters.
I am developing a website using PHP and MYSQL.
and i made a form to add categories for the blog and stored it in the table of categories.
Now i want to access those categories in the drop down menu in another form of blog . Can anyone solve my problem?
Here is the code of form:
<html>
<head>
<title>Create a Blog!</title>
</head>
<body>
<?php
include_once ('BlogClass.php');
$j = new Blog();
$ans = array();
$ans = $j->DisplayCategories();
?>
<form name="BlogTopic" action="BlogTopicProcess.php" method="post" onSubmit="return validateForm()">
topic_cat :
<select name="topic_cat">
<?php
for ( $i = 0; $i < count( $ans ); $i++ ) {
?>
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i] ['Category']);?></option>
<? php
}
?>
</select>
<label><strong>topic_id:</strong></label>
<input name="topic_id" type="text"/><br>
<label><strong>topic_subject:</strong></label>
<input name="topic_subject" type="text"/><br>
<label><strong>topic_date:</strong></label>
<input name="topic_date" type="text"/><br>
<label><strong>topic_by:</strong></label>
<input name="topic_by" type="text"/><br>
<input type="checkbox" name="terms" />
I agree to the terms & conditions <br>
<input type="submit" value="Create Topic" /><br>
</form>
</body>
</html>
The function DisplayCategory()
public function DisplayCategory() {
$connection=$this->Con->connectDb();
$data=array();
$sql="select * from categories";
$query=mysql_query($sql);
$numrows=mysql_num_rows($query);
if ($numrows!=0) {
while ($a=mysql_fetch_array($query))
$data[]=$a;
}
mysql_close($connection);
return $data;
}
I dont know what values your $ans contains, but this might help you
<select name='topic_cat'>
<?php foreach ( $ans as $a ) { ?>
<option value="<?php echo $a['key']?>"> <?php echo $a['value']; ?> </option>
<?php } ?>
</select>
Firstable you must delete the blank here
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i] ['Category']);?></option>
to
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i]['Category']);?></option>
if doesnt work then must check the method DisplayCategories() what type returns and in witch format.
Send us the code of this method
replace the code $data[]=$a; with this array_push($data,$a);
I need advice, what i did wrong and this code not working. In short I have droplist menu with data read from mysql database and I want this data what user selected put in to another table/row in db. with present code I received only NULL value in inserted row... some I assume maybe something wrong with syntax, I tried search similar topic and tried different way but result is same :| This is my code :
get function and form
<br><br>
<?php
include 'connectdb.php';
$sql="select * from persons";
$result=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$name_done.="<OPTION VALUE=\"$id\">".$name;
}
?>
<form action="insert.php" method="post">
<SELECT name="name_done" id="nane_done">
<OPTION VALUE=0>Choose Your name :
<?=$name_done?>
</SELECT> <br>
RFC: <input type="text" name="number"><br>
Date: <input type="text" id="datepicker" name="date">
<input type="submit" value="submit" />
</form>
And Insert
<?php
include 'connectdb.php';
$name_done = $_POST['nane_done'];
mysqli_query($con,"INSERT INTO rfc(name_done) VALUES (.$name_done)");
---- below working OK----
$sql = "INSERT INTO rfc(number,date)
VALUES
('$_POST[number]','$_POST[date]')";
if (!mysqli_query($con,$sql,$name_done))
{
die('Error: ' . mysqli_error($con));
}
echo "RFC added";
mysqli_close($con);
?>
You have a typo - "nane_done" rather than "name_done" in this line: $name_done = $_POST['nane_done'];.
Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.
i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereāthe second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.