问题描述
我使用JSON将值从表单发送到数据库。我的表(表tblstudent的名称)具有三列,即
name score pic
["aa","bb","cc"] ["525","523","562"] ["img1.png","img2.png","img3.png"]
如何从JSON编码中获取值并将其放入foreach循环中以获得类似的结果
img1.png
aa
525
image2.png
bb
523
image3.png
cc
562
以此类推
解决方法
您可以使用for循环并通过键设置索引
$name = ["aa","bb","cc"];
$score = ["525","523","562"];
$pic = ["img1.png","img2.png","img3.png"];
for($i = 0; $i < count($pic); $i++) {
echo $pic[$i] . PHP_EOL;
echo $name[$i] . PHP_EOL;
echo $score[$i] . PHP_EOL;
echo PHP_EOL;
}
输出:
img1.png
aa
525
img2.png
bb
523
img3.png
cc
562
,
我尝试将index.php
文件发送到request.php
,并将request.php
文件发送数据到json_decode
的形式并将数据打印到文件。
index.php
<!DOCTYPE html>
<html>
<head>
<title>send request</title>
<!--- jQuery cdn ----->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="display-data"></div>
</body>
</html>
<script type='text/javascript'>
$(document).ready(function () {
$.post('request.php',function (data,status) {
if (status == 'success') {
$('.display-data').append(data);
}
})
});
</script>
request.php
<?php
//This is a create a connection
$servername = 'localhost';
$dbname = "stackoverflow";
$username = "root";
$pass = "";
$conn = new PDO("mysql:host=$servername; dbname=$dbname;","$username","$pass");
//This is a create a connection end
$selectSql = "SELECT * FROM tblstudent";
$select = $conn->prepare($selectSql);
$select->execute();
for($i=0; $i<3; $i++) {
$data = $select->fetch();
$img[] = $data['image']; //This is a array of image
$name[] = $data['name']; //This is a array of name
$score[] = $data['score']; //This is a array of score
}
for($i=0; $i<3; $i++) {
echo $img[$i]."<br>"; //Print data to index.php file
echo $name[$i].'<br>'; //Print data to index.php file
echo $score[$i]."<br>"; //Print data to index.php file
echo '<br><br>';
}
?>