Trying to get MySQL to connect via php into JSON, but returning errors connecting to MySQL from a php script

◇◆丶佛笑我妖孽 提交于 2019-12-13 02:45:57

问题


Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error: Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13 Could not connect: Lost connection to MySQL server during query.

Also, line 13 is indicating the line in lib.php:

mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());

It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.

Lastly, I get the same error from both a localhost and a remote server using mysql

lib.php

<?

//Database Information

$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";


//Connect to database

mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());

//executes a given sql query with the params and returns an array as result
function query() {
    global $link;
    $debug = false;

    //get the sql query
    $args = func_get_args();
    $sql = array_shift($args);

    //secure the input
    for ($i=0;$i<count($args);$i++) {
        $args[$i] = urldecode($args[$i]);
        $args[$i] = mysqli_real_escape_string($link, $args[$i]);
    }

    //build the final query
    $sql = vsprintf($sql, $args);

    if ($debug) print $sql;

    //execute and fetch the results
    $result = mysqli_query($link, $sql);
    if (mysqli_errno($link)==0 && $result) {

        $rows = array();

        if ($result!==true)
        while ($d = mysqli_fetch_assoc($result)) {
            array_push($rows,$d);
        }

        //return json
        return array('result'=>$rows);

    } else {

        //error
        return array('error'=>'Database error');
    }
}

//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {

  $image = imagecreatefromjpeg($srcFile);
  $width = imagesx($image);
  $height = imagesy($image);

  $thumb = imagecreatetruecolor($sideInPx, $sideInPx);

  imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);

  imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);

  imagedestroy($thumb);
  imagedestroy($image);
}

?>

Index.php

<?
session_start();
require("lib.php");
require("api.php");

header("Content-Type: application/json");

switch ($_POST['command']) {
    case "login": 
        login($_POST['username'], $_POST['password']); break;

    case "register":
        register($_POST['username'], $_POST['password']); break;

}

exit();
?>

api.php

<?php

function errorJson($msg){
    print json_encode(array('error'=>$msg));
    exit();
}

function register($user, $pass) {
    //check if username exists
    $login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
    if (count($login['result'])>0) {
        errorJson('Username already exists');

//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
    //success
    login($user, $pass);
} else {
    //error
    errorJson('Registration failed');
}
}
}
function login($user, $pass) {
    $result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);

    if (count($result['result'])>0) {
        //authorized
        $_SESSION['IdUser'] = $result['result'][0]['IdUser'];
        print json_encode($result);
    } else {
        //not authorized
        errorJson('Authorization failed');
    }
}


?>

回答1:


As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.

Straight from the manual:

More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.

If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).




回答2:


I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost



来源:https://stackoverflow.com/questions/12702002/trying-to-get-mysql-to-connect-via-php-into-json-but-returning-errors-connectin

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