命名PHP对象和SQL问题。

时间:2017-06-24 01:26:10

标签: javascript php jquery mysql multidimensional-array

在一个名为:loadPosts.php的php文件中 我正在连接到数据库并检索VARCHAR,VARCHAR,TEXT,TEXT和VARCHAR。每个都有一个未定义的长度,我试图将数据放入一个对象。这是我的PHP代码。

    <?php

//Creates an array to keep track of all information being past back to java script
$info = array();

$i = 0;
$j = 0;

//If server sends a post method then execute script
if ($_SERVER["REQUEST_METHOD"] == "POST"){

    requestPosts($info);

    //Encode the array to be sent to the java script with all the return messages and the state
    echo json_encode($info);
}

function requestPosts(&$info){
    //Set name of server, username, password, and database to access
    $servername = "";
    $username = "";
    $passwordSQL = '';
    $dbname = "";

    //Create database connection
    $con = new mysqli($servername, $username, $passwordSQL, $dbname);

    //Check connection
    if ($con->connect_error) 
    {
        die("Connection failed: " . $con->connect_error);
        $info["message"] = "failed";
    }else{
        $info["message"]= "You're Connected!";
    }

    //Create a query for account name
    $sqlQuery = "SELECT * FROM posts;";

    //Send query and assign to result
    $result = $con->query($sqlQuery);

    //If result is set
    if($result){
        //If result has rows found
         if ($result->num_rows > 0) 
            {
                //Loop through result
                while($row = $result->fetch_assoc())
                {
                    $info[$i][$j] = $row;
                    $j += 1;
                }
            $i += 1;
            }
    }
}
?>

以下是我调用和检索数据的javascript:

$(function(){
   $.ajax({
            type: 'POST',
            url: 'assets/php/loadPosts.php',
            success: function (msg) {

                //Console log the message
                console.log('msg', msg);

                //Create an object from the message
                var obj = JSON.parse(msg);
                console.log('obj', obj);

            },
            error: function (msg) {
                alert('Form Error' + msg);
            }
        }); 
});

当我从我的java脚本中检索数据时,我得到了这个:

Return Code in Console

我想知道是否可以在包含所有子对象的数组中命名对象元素,以及让父对象中的第一个对象具有名称0而不是&#34;& #34;

提前感谢任何帮助或想法!我确信它很简单,我只是愚蠢,但我会喜欢这个帮助!谢谢:))

0 个答案:

没有答案