i have here a page for the registering a crew but i dont know what seems to be the problem. the query is working in phpmyadmin but not working in php page.
here is my code:
session_start();
require 'config.php';
if (#$_SESSION['username']) {
if (isset($_POST['first_name'])&&isset($_POST['middle_name'])&&isset($_POST['last_name'])&&isset($_POST['age'])&&isset($_POST['birth_date'])&&isset($_POST['birth_place'])&&isset($_POST['gender'])&&isset($_POST['martial_status'])&&isset($_POST['religion'])&&isset($_POST['nationality'])&&isset($_POST['email'])&&isset($_POST['address1'])&&isset($_POST['address2'])&&isset($_POST['course'])&&isset($_POST['school'])&&isset($_POST['remarks'])) {
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$age = $_POST['age'];
$birth_date = $_POST['birth_date'];
$birth_place =$_POST['birth_place'];
$gender = $_POST['gender'];
$martial_status = $_POST['martial_status'];
$religion = $_POST['religion'];
$nationality = $_POST['nationality'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$course = $_POST['course'];
$school = $_POST['school'];
$remarks = $_POST['remarks'];
$date_added = date('Y-m-d');
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else {
echo 'Some field is empty';
}
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Add New Crew</title>
</head>
<body>
<form action="add_crew.php" method="POST">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="first_name" ></input>
</td>
</tr>
<tr>
<td>
Middle Name:
</td>
<td>
<input type="text" name="middle_name" ></input>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="last_name" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Age:
</td>
<td>
<input type="text" name="age" ></input>
</td>
</tr>
<tr>
<td>
Birth Date:
</td>
<td>
<input type="text" name="birth_date" ></input>
</td>
</tr>
<tr>
<td>
Birth Place:
</td>
<td>
<input type="text" name="birth_place" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Gender:
</td>
<td>
<input type="text" name="gender" ></input>
</td>
</tr>
<tr>
<td>
Martial Status:
</td>
<td>
<input type="text" name="martial_status" ></input>
</td>
</tr>
<tr>
<td>
Religion:
</td>
<td>
<input type="text" name="religion" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Nationality:
</td>
<td>
<input type="text" name="nationality" ></input>
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<input type="text" name="email" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Address 1:
</td>
<td>
<input type="text" name="address1" ></input>
</td>
</tr>
<tr>
<td>
Address 2:
</td>
<td>
<input type="text" name="address2"></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Course:
</td>
<td>
<input type="text" name="course" ></input>
</td>
</tr>
<tr>
<td>
School Graduated:
</td>
<td>
<input type="text" name="school" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Remarks:
</td>
<td>
<input type="text" name="remarks"></input>
</td>
</tr>
</table><br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>';
}
else { header('Location: /practice1/index.php');
}
?>
this is the entire page of php
Just like Saty say you forget to insert query
$conn->query($query); // PDO for new php7
mysql_query($query,$conn); // for old code but this is deprecated
//$conn is mysql_connect in config.php (it's may be in another variable up on your write)
<?php if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status)
VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
// for mysqli code starts
mysqli_query($con, $query);
// for mysqli code ends where $con is connection variable
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
?>
you have to fire the query to insert in database , i think you forgot
add this code after your query to execute it
if (mysqli_query($conn,$query)) {
echo 'Your request is sent to queue';
}
else {
echo 'Something went wrong';
}
I think you missed Two points
1.connection between your php and mysql.
2.Firing the query.
Try with this snippet.
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$conn = mysql_connect($dbhost, $username, $password);
//connection to the database
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
and then put
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
After that fire your query
if (mysqli_query($conn,$query))
{
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else
{
echo 'Some Syntax is wrong';
}
}
else {
echo 'Some field is empty';
}
And close the connection after used by
mysql_close($conn);
#prakash above is the closest to correct...
however, i think, set all of your inputs on your html with value="", so that you do not have to do all of the if(!empty() garbage and get blanks later...
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$dbname = "your_db";
// just good practice to specify the db, later you may have multiple on the same server..
// use mysqli as someone else above stated...
$conn = mysqli_connect($dbhost, $username, $password,$dbname);
if(!$conn){
die('Connect Error: ' . mysqli_connect_error());
//again.. mysqli.. not mysql
}
// dont kill yourself with manual entry errors for the query...
// move $_POST to a new variable and prep the array for a loop;
$data = $_POST;
// get rid of the submit variable
unset($data['submit']);
// assuming this db field is int not varchar
// and assuming birthdate field is DATE or varchar
$data['age'] = intval($data['age']);
$data['birthdate'] = date('Y-m-d',strtotime($date['birthdate']));
// would be easier to set default value NOW() for date_added column and DATETIME
// NOW() will set that field to the CURRENT_TIMESTAMP on every insert for you...
// but the way you have it, and assuming db field is DATE or varchar
$data['date_added'] = date('Y-m-d');
// Same for 'crew_status' .. field VARCHAR or ENUM... default value 'PENDING'
$data['crew_status'] = 'PENDING';
// make a string variable to fill with fields...
$fields = '';
// make a string variable to to fill with insert values....
$values = '';
// loop through $data, add each value followed by a comma to string
// no single quotes on integers where the db field is INT .... like age...
foreach($data as $key=>$val){
// this is looking for the value="" from when a user blanks an input field....
if($val == ''){
// handles blank user inputs.. db fields NOT set 'not null'..no quotes around NULL
$values .= 'NULL,';
// if the value is not blanked... look for strings and dates....
}elseif(!is_int($val)){
// real_escape_string will kill any characters that will error like ' or \
// and remove in sql injection risks .. single quotes on varchar db field vals
$values .="'".mysqli_real_escape_string($conn,$val)."',";
// if input is not blank and !is_int() must be INT...age
}else{
//no quotes on integers going into INT db fields....
$values .= $val.',';
}
// add the $key (field name) to the $fields same order as $values, comma after each
// backticks around field names...
$fields .= "`".$key."`,";
}
// we are dragging an extra comma on $fields and $values at the end of each string
// we will get them in the insert query string....splitting up the query to explain
$query = "INSERT INTO `crew_info`";
//substr off the comma $fields is dragging "," put it between ( and )
$query .= "(".substr($fields,0,-1).")";
//substr off the comma $values dragging "," put it between ( and )
$query .= " VALUES (".substr($values,0,-1).")";
//not split query might be confusing to read..query would look like...
//"INSERT INTO `crew_info`(".substr($fields,0,-1).") VALUES (".substr($values,0,-1).")"
//now insert
if(!mysqli_query($conn,$query)){
// if there is an error... let someone know!
die('ooops!...'.mysqli_error());
}else{
// if no error......
echo 'you just inserted data!!! id# = '. mysqli_insert_id($conn);
}
There is an error in your sql string. INSERT INTO table VALUES(..,..);
$query = "INSERT INTO `crew_info` VALUES (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
So I'm having a challenge with a subscription system that I've been building.
I'm using a simple login php page to validate the username and password of the user against the DB, once authenticated the script creates a secure session and calls the edit_subscription.php file and passes the ID of the user through the Url.
The edit_subscription.php file takes the ID and pulls the user info using MYsql
and loads their info into a form. The user can then edit or modify their subscription details and press the submit button to update the DB.
Everything works except the mysql Update back to the DB.
I've managed to narrow the problem down to the ID variable
If I hardcode the variable into the update command it works and the db is updated
If I hardcode the ID into a variable used in the update command, it works up to a point. if I move that hardcoded variable in front of line 42 the update command will no longer work.
I think it's something to do with the post command, but even when I load the old ID into a hidden form and try to have it repost for the update command it still doesn't work and treats the variable as if it's empty.
I've tried for hours to get this working, and just can seem to get it going.
anyone have any suggestions pertaining to specifically this issue
(please don't comment of security or, best practices unless it relates specifically to the issue described thanks)
<?
$id = htmlspecialchars($_GET['ID']);
$username="****";
$database="****";
$host="****";
$pass ="****";
mysql_connect($host,$username,$pass);
#mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT * FROM `****`.`****` WHERE `Subscriber ID` = '$id' LIMIT 1");
$name_old=mysql_result($result,0,"Name");
$address1_old=mysql_result($result,0,"Address 1");
$address2_old=mysql_result($result,0,"Address 2");
$city_old=mysql_result($result,0,"City");
$prov_old=mysql_result($result,0,"Prov");
$postal_old=mysql_result($result,0,"Postal");
$country_old=mysql_result($result,0,"Country");
$email_old=mysql_result($result,0,"Email");
$qty_old=mysql_result($result,0,"qty");
$status_old=mysql_result($result,0,"Status");
$ezine_old=mysql_result($result,0,"Ezine");
$mailout_old=mysql_result($result,0,"Mailout");
$password_old=mysql_result($result,0,"Password");
$nameErr = $emailErr = $passwordErr = "";
$name=$_POST['name'];
$email=$_POST['email'];
$address1=$_POST['address1'];
$address2=$_POST['address2'];
$city=$_POST['city'];
$province=$_POST['prov'];
$postal=$_POST['postal'];
$country=$_POST['country'];
$password=$_POST['password'];
$mailout=$_POST['mailout'];
$ezine=$_POST['ezine'];
$status="Subscribed";
$qty=$_POST['qty'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passwordErr = "* Password is required";
}
if (empty($_POST["name"])) {
$nameErr = "* Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "* Invalid Characters";
}
}
if(isset($_POST['mailout'])){}
else{
$mailout="NO";
}
if(isset($_POST['ezine'])){}
else{
$ezine="NO";
}
if (empty($_POST["email"])) {
$emailErr = "* Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid email";
}
}
if($name != NULL AND $nameErr == ""){
if($email != NULL AND $emailErr == ""){
if($password != NULL AND $passwordErr == ""){
mysql_query("UPDATE `Subscribers` SET
`Name` ='$name',
`Email` = '$email',
`Address 1` = '$address1',
`Address 2` = '$address2',
`City` = '$city',
`Prov` = '$province',
`Postal` = '$postal',
`Country` = '$country',
`Password` = '$password',
`qty` = '$qty',
`Status` = '$status',
`Mailout` = '$mailout',
`Ezine` = '$ezine',
WHERE `Subscriber ID` = $id");
mysql_close();
echo ("<p align=\"center\"><font color=\"red\">Thank you for updating your subscription, you should receive an email confirmation shortly</font></p>");
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="100%" border="0">
<tr>
<td width="11%" align="right">Name</td>
<td width="3%"> </td>
<td width="47%"><input type="text" name="name" value="<?php echo $name_old;?>">
<font color="red"> <?php echo $nameErr;?></font></td>
<td width="39%" bgcolor="#CCCCCC"><input type="checkbox" name="ezine" value="YES"
<? if($ezine_old =="YES"){echo "checked";} ?>>
Subscribe by email</td>
</tr>
<tr>
<td width="11%" align="right">Address 1</td>
<td> </td>
<td width="47%"><input type="text" name="address1" value="<?php echo $address1_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="checkbox" name="mailout" value="YES" <? if($mailout_old =="YES"){echo "checked";} ?>>
Subscribe by Post </td>
</tr>
<tr>
<td width="11%" align="right">Address 2</td>
<td> </td>
<td width="47%"><input type="text" name="address2" value="<?php echo $address2_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="text" name="qty" value="<?php echo $qty_old;?>" size="5">
# of copies.</td>
</tr>
<tr>
<td align="right">City</td>
<td> </td>
<td><input type="text" name="city" value="<?php echo $city_old;?>"></td>
<td> </td>
</tr>
<tr>
<td align="right">Province</td>
<td> </td>
<td><input type="text" name="prov" value="<?php echo $prov_old;?>" >
<td> </td>
</tr>
<tr>
<td align="right">Postal</td>
<td> </td>
<td><input type="text" name="postal"value="<?php echo $postal_old;?>" ></td>
<td></td>
</tr>
<tr>
<td align="right">Country</td>
<td> </td>
<td><input type="text" name="country" value="<?php echo $country_old;?>" ></td>
<td> </td>
</tr>
<tr>
<td align="right">Email</td>
<td> </td>
<td colspan="2"><input type="text" name="email" value="<?php echo $email_old;?>">
<font color="red"><?php echo $emailErr;?></font></td>
</tr>
<tr>
<td align="right">Password</td>
<td> </td>
<td colspan="2"><input type="password" name="password" value="<?php echo $password_old;?>">
<font color="red"> <?php echo $passwordErr;?></font></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td align="right"> </td>
<td><img src="images/shim.png" width="20" height="20" /></td>
<td><input type="Submit" ></td>
<td> </td>
</tr>
</table>
<p> </p>
</form>
There is a comma after
Ezine = '$ezine' ,
Remove it. Also you shall also use mysqli extension or PDO sql . mysql_ is deprecated
As you said, there is a lot wrong with that code.. however to satisfy your question here is the simple answer:
You left an extra comma in your update statement.
`Ezine` = '$ezine',
In the future try always checking if the query went through.
$result = mysql_query(..);
if($result) {
// it worked
} else {
// it failed
echo mysql_error(); // or mysqli_error($link); or $link->error, etc.
}
Best of luck
At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];
I just need to insert my form data into mysql database & display it in browser. But, when I fill up the form & click submit , the row gets added but with no data except for ID field which is autoincremented.. even the table in phpmyadmin looks same with the row added & empty fileds.
any suggestions will be highly appreciated...
my html form looks like this,
<table border="1">
<tr>
<td align="center">Form Input Students Data</td>
</tr>
<tr>
<td>
<table>
<form method="POST" action="data_insert_htmlform.php/">
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="name" size="20">
</td>
</tr>
<tr>
<td><label for="Age">Age</label></td>
<td><input type="text" name="age" size="20">
</td>
</tr>
<tr>
<td><label for="Birth_Date">Birth_Date</label></td>
<td><input type="text" name="Birth_Date" size="20">
</td>
</tr>
<tr>
<td><label for="Address"Address</label></td>
<td><input type="text" name="address" size="40">
</td>
</tr>
<tr>
<td></td>
<td align="center">
<input type="submit" name="submit" value="Sent">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
and my php code,
<?php
error_reporting(E_ERROR | E_PARSE);
$database = 'students';
$continued=mysql_connect("localhost" , "root", "");
if(mysql_select_db($database))
echo ("<br><br>connection to the database succeeds");
else
echo ("connection failed");
/*$name = $_POST['name'];
$age = $_POST['age'];
$birth_date = $_POST['Birth_date'];
$address = $_POST['address'];*/
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}')";
$abc = mysql_query($insert);
if($abc){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");
}
$order = "SELECT * FROM students_basicinfo";
$result = mysql_query($order);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<table border='1'>";
while($data = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$data[ID]."</td>";
echo "<td>".$data[Name]."</td>";
echo "<td>".$data[Age]."</td>";
echo "<td>".$data[Birth_Date]."</td>";
echo "<td>".$data[Address]."</td>";
echo "</tr>";
}
echo "</table>";
?>
This issue about input name case sensitive
Change $_POST['Birth_date'] to $_POST['Birth_Date'] with uppercase D
Try following query, this will work.
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_Date']}' , '{$_POST['address']}')";
Replace
'{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}'
with
'".$_POST['name']."','".$_POST['age']."' , '".$_POST['Birth_date']."' , '".$_POST['address']."'
Try :
echo "<tr>";
echo "<td>".$data['ID']."</td>";
echo "<td>".$data['Name']."</td>";
echo "<td>".$data['Age']."</td>";
echo "<td>".$data['Birth_Date']."</td>";
echo "<td>".$data['Address']."</td>";
echo "</tr>";
(Use prepared statements.)
Dump the statement, in a HTML comment <!-- ... ---> so you can try it yourself.
Use echo mysql_error() to check for errors.
I mistrust the date field, DATE? Use '2013-08-31or '2013-08-31 14_:07 / '2013-08-31T14_:07`.
I am trying to update a table in my DB for the past two days. But I am unable to get it to work. Somebody please help me.
I could connect to my database, see my table fields perfectly. Posted values from the form could be read perfectly from the destined PHP file.
MySQL query doesn't seen to return any error.
But I dont understand why the values are not getting updated into the table.
//form.html
<form name="account" action="test.php" method="post">
<td align="left" valign="top" class="labelstyle" width="25%">First Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="fname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Last Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="lname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Email</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="email" value="" /></td>
<td align="left" valign="top" class="labeltextstyle"><input type="submit" name="submit" value="Save" /></td>
</form>
// test.php
<?php
$dbhost = "localhost";
$dbname = "test";
$dbuser = "";
$dbpass = "";
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
if(isset($_REQUEST['submit'])){
// $query = "select * from form";
// $result = mysql_query($query);
// $numcolumn = mysql_num_fields($result);
// for ( $i = 0; $i < $numcolumn; $i++ ) {
// $columnnames = mysql_field_name($result, $i);
// echo $columnnames;
// }
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
echo $fname ;
echo $lname ;
echo $email ;
$query = "update test set
fname = $fname,
lname = $lname,
email = $email
where 1 ";
$result = mysql_query($query);
if ($query = 1) {
echo "IT WORKED";
} else {
echo "DIDNT WORK";
}
}else{
echo "NOT SUBMITTED";
}
?>
//form.html
<form name="account" action="test.php" method="post">
<td align="left" valign="top" class="labelstyle" width="25%">First Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="fname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Last Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="lname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Email</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="email" value="" /></td>
<td align="left" valign="top" class="labeltextstyle"><input type="submit" name="submit" value="Save" /></td>
</form>
When i fill the form with values A, B and C and submit the form, I get the following output.
fnamelnameemailABCIT WORKED
please help me soon.
There is no id in the where clause to indicate which row must be updated. This will update all the rows in the table. It should look like this:
$query = "update test set
fname = $fname,
lname = $lname,
email = $email
where id = 1";
I assume that a row is created beforehand so that you know which row to update. If not then rather use an INSERT statement should be used.
$query = "insert into test (fname,lname,email) VALUES ($fname,$lname,$email);
fname, lname and email are strings, which have to be escaped in the SQL query:
$query = "update test set
fname = '$fname',
lname = '$lname',
email = '$email'
where 1";
You probably can leave the where 1 as well.