将数据插入数据库的PHP脚本在执行时返回成功但记录未插入数据库?
Posted
技术标签:
【中文标题】将数据插入数据库的PHP脚本在执行时返回成功但记录未插入数据库?【英文标题】:PHP script inserting data into db return success on execution but record is not inserted in db? 【发布时间】:2019-01-28 00:11:00 【问题描述】:strong text以下是用于将记录插入数据库的代码。脚本正在执行,因为记录没有插入数据库,但是 php 脚本正在执行而没有任何失败。请帮我解决这个问题。
<?php
$servername = "xxx.xx.x.xxx";
$username = "usr";
$password = "pwd";
$dbname = "Dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$postdata = json_decode(file_get_contents('php://input'), true);
$tablename = "tablename";
function guidv4($data)
assert(strlen($data) == 16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
if(is_array($postdata))
$sql = "INSERT INTO ".$tablename." (id, ssid, address, lat, lng, state, country, city, cat, subcat, sname, createdAt,pincode) VALUES ";
$valuesArr = array();
foreach($postdata as $row)
//$loc = explode(", ", $row['loc']);
//$lat = mysqli_real_escape_string($conn, $loc[0]);
//$lng = mysqli_real_escape_string($conn, $loc[1]);
$id = guidv4(random_bytes(16));
//$id = mysqli_real_escape_string($conn, $row['id']);
$ssid = mysqli_real_escape_string($conn, $row['sname']);
$address = mysqli_real_escape_string($conn, $row['address']);
$lat = mysqli_real_escape_string($conn, $row['lat']);
$lng = mysqli_real_escape_string($conn, $row['lng']);
$state = mysqli_real_escape_string($conn, $row['state']);
$country = mysqli_real_escape_string($conn, "India");
$city = mysqli_real_escape_string($conn, $row['city']);
$cat = mysqli_real_escape_string($conn, $row['cat']);
$subcat = mysqli_real_escape_string($conn, $row['subcat']);
$sname = mysqli_real_escape_string($conn, $row['sname']);
$createdAt = mysqli_real_escape_string($conn, $row['createdAt']);
$pincode = mysqli_real_escape_string($conn, $row['pincode']);
$valuesArr[] = "('$id', '$ssid', '$address', '$lat', '$lng', '$state', '$country', '$city', '$cat', '$subcat', '$sname', '$createdAt','pincode')";
$sql .= implode(',', $valuesArr);
$conn->query($sql) or exit(mysql_error());
$conn->close();
?>
【问题讨论】:
【参考方案1】:$valuesArr 数组元素似乎没有正确连接
您应该使用连接运算符“.”将 PHP 变量与文本分开,如下所示:
$valuesArr[] = "('" . $id ."', '" .$ssid . "', '" . $address ."', '" . $lat ."', '" . $lng . "', '" $state . "', '" . $country . "', '" . $city . "', '" . $cat . "', '" . $subcat ."', '" . $sname . "', '" . $createdAt . "','pincode')";
【讨论】:
以上是关于将数据插入数据库的PHP脚本在执行时返回成功但记录未插入数据库?的主要内容,如果未能解决你的问题,请参考以下文章
如何将验证错误从 php 返回到 swift 或 segue 成功