Load mysqli php data via ajax call

被刻印的时光 ゝ 提交于 2019-11-29 12:34:01

Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to

function ajaxCall(category)
{
    $.ajax({
        url: 'test.php',
        type: "GET",
        data: {cat: category},
        dataType: 'json',    
        success: function(rows) {
           alert(rows);
        },
        error: function() {
           alert("An error occurred.");
        }
    });
}

and call it using

ajaxCall('css');

I just rewrote the php code using PDO, should be more safe now.

db.php

<?php

$dbhost = "localhost";  

$dbuser = "root";

$dbpsw = "somepsw";    

$dbname= "blog"; 

try {

    @$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
}

catch(PDOException $e) {

    echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
    getErrorsLog($e->getMessage());
 }

 function closeDbConn () {

    $dbh = null;

 }

 function getErrorsLog($message) {

    $file = 'dberrors.log';
    $date = date("d/m : H:i :");

    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new error message to the file
    $current .= $date.$message;
    $current .= "\r\n";
    // Write the contents back to the file
    file_put_contents($file, $current);
    exit();

 }

?>

blogdata.php

<?php

include_once "db.php";

$tableName = "posts";
$data = array();
@$view = $_GET["view"];

if (isset($_GET["view"])) { 

    $stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC"); 
 }
 else {  

    try {

    $stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");

    }

    catch (PDOException $e) {

        getErrorsLog($e->getMessage());

    }

 }

$stmt->bindValue(1, $view, PDO::PARAM_STR);

$stmt->execute();

$affected_rows = $stmt->rowCount(); //Rows count

 if ($affected_rows == 0) {

     echo "The data you looking for no longer exist, please contact the administrator.";
     exit();
 }

foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {

    $data[] = $row;

 }

echo json_encode($data);

closeDbConn();

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!