[英]form data insert in database with one foreign key columns in php
I am trying to insert contact form into database.我正在尝试将联系表格插入数据库。
1.) I am trying to insert contact form without foreign key working fine. 1.)我正在尝试插入没有外键工作正常的联系表格。
2.) But form data insert with other table foreign key columns not working. 2.) 但是表单数据插入与其他表外键列不起作用。
control.php
if(isset($_REQUEST['submit']))
{
$co_name=$_REQUEST['co_name'];
$co_email=$_REQUEST['co_email'];
$co_subject=$_REQUEST['co_subject'];
$co_comment=$_REQUEST['co_comment'];
$data=array("co_name"=>$co_name,"co_email"=>$co_email,"co_subject"=>$co_subject,"co_comment"=>$co_comment);
$res=$this->insert('customer_contact',$data);
if($res)
{
echo"sucess";
}
else
{
echo "Wrong";
}
}
This is model.php
code这是model.php
代码
<?php
class model
{
public $conn="";
function __construct()
{
$this->conn=new MySQLi("localhost","root","mohit@75","new_healthy_life");
}
function select($tbl)
{
$sel="SELECT * FROM $tbl";
$exc=$this->conn->query($sel);
while($fetch=$exc->fetch_object())
{
$arr[]=$fetch;
}
return $arr;
}
function insert($tbl,$data)
{
$col_arr=array_keys($data);
$col=implode(",",$col_arr);
$value_arr=array_values($data);
$value=implode("','",$value_arr);
echo $insert="INSERT INTO `$tbl`($col) value('$value')";
$exc=$this->conn->query($insert);
return $exc;
}
}
Below contact table image下面的联系表图片
My Actual question is form data how to insert with foreign key.我的实际问题是如何使用外键插入表单数据。
Show image:-显示图像:-
How to solve this...如何解决这个...
Thanks...谢谢...
I will just modify your insert function and return inserted id:我将修改您的插入 function 并返回插入的 id:
function insert($tbl,$data)
{
$col_arr=array_keys($data);
$col=implode(",",$col_arr);
$value_arr=array_values($data);
$value=implode("','",$value_arr);
echo $insert="INSERT INTO `$tbl`($col) value('$value')";
$exc=$this->conn->query($insert);
$last_id = $this->conn->insert_id;
return $last_id;
}
Now in your control.php
现在在您的control.php
if(isset($_REQUEST['submit']))
{
$co_name=$_REQUEST['co_name'];
$co_email=$_REQUEST['co_email'];
$co_subject=$_REQUEST['co_subject'];
$co_comment=$_REQUEST['co_comment'];
$data=array("co_name"=>$co_name,"co_email"=>$co_email,"co_subject"=>$co_subject,"co_comment"=>$co_comment);
$res=$this->insert('customer_contact',$data);
if($res)
{
//
$data=array("foreignkey_col1"=>$foreignkey_col1_data,"foreign_key"=>$res);
$res1=$this->insert('foreign_key_table',$data);
if($res1)
{
//inserted into master table as well
}
else
{
//issue while inserting into master table
}
}
else
{
echo "Wrong";
}
}
I am not sure about your other table name of foreign key so I have just kept static and sample data but you see now $res
will return inserted id and that you can use to insert into another table name as well by writing another insert query.我不确定您的外键的其他表名,所以我只保留了 static 和示例数据,但您现在看到$res
将返回插入的 id,您也可以通过编写另一个插入查询来插入另一个表名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.