尝试在数据库中采用 JSON,因为我的数据不固定。我可以从终端很好地查询,并且需要将相同的查询写入 php 脚本。我花了很多时间才问。例子:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
其中 id = 35 将成为 $ _POST ['id'] 的变量
我尝试了什么:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
我哪里做错了?
我在 SO https://stackoverflow.com/a/33433552/1273715上遵循了这个答案, 但我需要在 php 中移动查询以进行 ajax 调用
可能的另一个帮助。
$ajax 调用的结果可以用作键值还是保留字符串?另一方面,我可以将字符串转换为对象,例如学生 = new Object()?
我在 js 环境中需要的 eaxaple - 计算数组中的对象 - 并循环键值
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
在这里我想避免使用反斜杠
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
非常感谢任何可能的帮助
UPDATE
离开 json_extract() 函数我已经解决了第二个问题,所以现在我可以使用对象属性,最后对数组中的对象进行计数很重要:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js部分
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
奇怪的行为:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup 是对的,但是
console.log(result.lenght);
output is null