简体   繁体   中英

Query json_extract with PDO and SQLIte db

Try to adopt JSON in database because i have data not fixed. i can query well from terminal, and need to write same query to php script. i have spent a lot of time before ask. example:

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"}]

where id = 35 will become a variable of $ _POST ['id']

what I tried:

$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"}]

where did I go wrong?

I followed this answer on SO https://stackoverflow.com/a/33433552/1273715 but i need to move the query in php for an ajax call

possibile another help.

Can the result fron $ajax call can be usable as key value or remain string? in other hands i can convert string to object like students = new Object()?

eaxaple of what i need in js environment - count objects in array - and loop key value

var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));

here I would like to avoid the backslash

consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2

any possible help is largely appreciated

UPDATE

leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:

<?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 part

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!

odd behaviour:

console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa

outup is right but

 console.log(result.lenght);
output is null

You are surrounding you query with double quotes but inside the query there is an unescaped $ .

Try escaping it:

$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));

You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.

I also include php mysql backend workability for clarity. so Yo have now two options

1.) PHP WITH MYSQL

2.) PHP WITH SQLITE as you requested

index.html

<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">

$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){

var length = data.length;
for(var s=0; s<length; s++){

var student_id = data[s].student_id;
var student_name = data[s].student_name;


var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";

$("#Result").append(res);

}
}

    });

});


</script>

<body>
<div id="Result" ></div>
</body>

In mysql database you can do it this way.

<?php

$host = "localhost"; 
$user = "ryour username"; 
$password = "your password"; 
$dbname = "your bd name";

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}

$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);

while($row = mysqli_fetch_array($result)){
    $student_id = $row['student_id'];
    $student_name = $row['student_name'];

    $return_arr[] = array("student_id" => $student_id,
                    "student_name" => $student_name);
}

// Encoding array in JSON format
echo json_encode($return_arr);

?>

So with sqlitedb something like this will work for you

$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());

//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));

while($row = $result2->fetch()){
    $student_id = $row['student_id'];
    $student_name = $row['student_name'];

    $return_arr[] = array("student_id" => $student_id,
                    "student_name" => $student_name);
}

// Encoding array in JSON format
echo json_encode($return_arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM