Can JavaScript connect with MySQL?

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

Can JavaScript connect with MySQL? If so, how?

19条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 16:56

    No.

    You need to write a wrapper in PHP, and then export the returned data (probably as Json). NEVER, get from your "_GET" the SQL code, as this is called an SQL injection (people who learn this will have full control over your database).

    This is an example I wrote:

    function getJsonData()
    {
            global $db;
            if (!$db->isConnected()) {
                   return "Not connected";
            }
            $db->query("SELECT * FROM entries");
            $values = array();
            while( $v = $db->fetchAssoc()){
                    $values[] = $v;
            }
            return json_encode($values);    
    }
    
    switch (@$_GET["cmd"]){
            case 'data':
                    print getJsonData();
                    exit;
    
            default:
                    print getMainScreen();
                    exit; 
    }
    

    Do learn about SQL injections please.

提交回复
热议问题