使用主/外键在php中更新数据

时间:2014-02-11 20:00:57

标签: php mysql

表单脚本:

 <?php
// Inialize session
//session_start();
// Check, if username session is NOT set then this page will jump to login page
/*if (!isset($_SESSION['email'])) {
header('Location: form.html');
}*/
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'online');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
//inserting Record to the database
$name = $_POST['name'];
$fname = $_POST['fname'];
$cnic =  $_POST['cnic'];
$cellno = $_POST['cellno'];
$nationality = $_POST['nationality'];
$gender =  $_POST['gender'];
$dob = $_POST['dob'];
$religion = $_POST['religion'];
$city=$_POST['city'];
$email = $_POST['email'];
$adress = $_POST['adress'];

 if(!empty ($_POST['name']) && ($_POST['fname']) && ($_POST['cnic']) && ($_POST['cellno']) && ($_POST['nationality']) && (($_POST['gender']==='male')||($_POST['gender']==='female')) && ($_POST['dob']) && ($_POST['religion']) && (($_POST['city']==='Karachi')||($_POST['city']==='Isalamabad')||($_POST['city']==='Lahore')||($_POST['city']==='Rawalpindi'))  && ($_POST['adress']))   //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$query = "INSERT INTO basicinfo(name,fname,cnic,cellno,nationality,gender,dob,religion,city,adress)VALUES('$name','$fname','$cnic','$cellno','$nationality','$gender','$dob','$religion','$city','$adress')";
$update = "UPDATE basicinfo SET name='$name',fname='$fname',cnic='$cnic',cellno='$cellno',nationality='$nationality',gender='$gender',dob='$dob',religion='$religion',city='$city',adress='$adress' WHERE bid=";

$result = mysql_query($query);
$updateResult=mysql_query($update);
if($result && updateResult)
    {
        echo "Successfully updated database";
        header('Location: academicinfo.html');
    }
    else
    {
     die('Error: '.mysql_error($con));
    }
    mysql_close($con);
    }
    else{
    header('Location: basicinfo.html');
    }
if (isset ($_POST['neext']))
{
header ('location:academicinfo.html');
}

?>

这是我想要更新数据的php代码,但我不知道在where子句中写什么,因为在MySQL数据库bid列是自动增量而且是外键请帮帮我对此。

1 个答案:

答案 0 :(得分:1)

非常简单,只需将它用于适合您的情况。这将在您的查询中添加另一个选择,但它不是那么大,因为它是内联的。那是你选择的桌子吗?


$update = "UPDATE basicinfo SET name='$name',fname='$fname',cnic='$cnic',cellno='$cellno',nationality='$nationality',gender='$gender',dob='$dob',religion='$religion',city='$city',adress='$adress' WHERE bid= (SELECT bid FROM basicinfo ORDER BY bid ASC LIMIT 1)";