Can JavaScript connect with MySQL?

前端 未结 19 2105
小鲜肉
小鲜肉 2020-11-22 16:18

Can JavaScript connect with MySQL? If so, how?

19条回答
  •  我在风中等你
    2020-11-22 16:50

    JavaScript can't connect directly to DB to get needed data but you can use AJAX. To make easy AJAX request to server you can use jQuery JS framework http://jquery.com. Here is a small example

    JS:

    jQuery.ajax({
    type: "GET",
    dataType: "json",
    url: '/ajax/usergroups/filters.php',
    data: "controller=" + controller + "&view=" + view,
    success: function(json)
    {
        alert(json.first);
        alert(json.second);
    });
    

    PHP:

    $out = array(); 
    
    // mysql connection and select query
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    
    try {
      die("Connection failed: " . $conn->connect_error);
    
      $sql = "SELECT * FROM [table_name] WHERE condition = [conditions]";
      $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
      // output data of each row
      while($row = $result->fetch_assoc()) {
        $out[] = [
           'field1' => $row["field1"],
           'field2' => $row["field2"]
        ];
      }
    } else {
      echo "0 results";
    }
    
    } catch(Exception $e) {
      echo "Error: " . $e->getMessage();
    }
        echo json_encode($out);
    

提交回复
热议问题