gpt4 book ai didi

php - 查询条件以从表单中插入数据

转载 作者:行者123 更新时间:2023-11-29 07:16:42 25 4
gpt4 key购买 nike

我想做的是:

如果在我的表单中输入的年龄 = 28、30、25 或 21,那么我想在列 (VE) 中自动插入值 8,否则将其留空。这是正确的做法吗?

if($form_data->action == 'Insert')
{

$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);

if($form_data->age == $age_str){

$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);


if($statement->execute($data))
{
$message = 'Data Inserted';
}
}


此外,如何将来自其他表单数据的行 ID 插入到tbl 中的新行

最佳答案

使用php's in_array而不是尝试比较字符串。要获取插入表单数据的查询的 ID,您可以 return the id of the insert row from your prepared statement .

if ($form_data->action == 'Insert') {

// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);

$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);

if ($statement->execute($data)) {
$message = 'Data Inserted';

// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();

// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);

// in_array uses your array...so you don't need
// if($form_data->age == $age_str){

if (in_array($form_data->age, $ages_to_insert)) {

$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

关于php - 查询条件以从表单中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com