gpt4 book ai didi

php - 如何使用php变量作为表名在mysql中插入记录

转载 作者:行者123 更新时间:2023-11-29 20:43:57 25 4
gpt4 key购买 nike

$id = $_SESSION['id'];

我将表名称存储在 $id 变量中。

当我在 sql 查询中使用变量名称时,它不起作用

$sql = "INSERT INTO karthick.$id (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";

当我将 karthick.$id 替换为 karthick.ford 时,它工作正常。但我想使用存储在 $id 中的变量作为我的表名。我该怎么做。

编辑----------------------------------------我的 PHP 代码

<?php
session_start();
$id = $_SESSION['id'];
require 'database.php';
/*$sql = "CREATE TABLE karthick.details (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL)";
if($conn->query($sql)===TRUE){
echo "table created";
}else{
echo "table not created";
}*/

$name = mysqli_real_escape_string($conn, $_POST["cname"]);
$tin = mysqli_real_escape_string($conn, $_POST["tin"]);
$address = mysqli_real_escape_string($conn, $_POST["address"]);
$product = mysqli_real_escape_string($conn, $_POST["product"]);
$ddate = mysqli_real_escape_string($conn, $_POST["date"]);
$invoice = mysqli_real_escape_string($conn, $_POST["invoice"]);
$transport = mysqli_real_escape_string($conn, $_POST["transport"]);
$cutting = mysqli_real_escape_string($conn, $_POST["date"]);
$amount = mysqli_real_escape_string($conn, $_POST["amount"]);
$vat = mysqli_real_escape_string($conn, $_POST["vat"]);
$val = 'karthick'.$id;
echo $val;
$sql = "INSERT INTO $val (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
if($conn->query($sql)===TRUE){
echo "record inserted";
}else{
echo "not inserted".$conn->error;
}
$conn->close();
?>

最佳答案

试试这个。

$val = 'karthick'.$id;
$sql = "INSERT INTO $val (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";

关于php - 如何使用php变量作为表名在mysql中插入记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502212/

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