无法在服务器中插入信息,但我可以作为本地主机 [英] Can't insert info in a server, but i can as localhost

查看:38
本文介绍了无法在服务器中插入信息,但我可以作为本地主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序,但是我无法使用Mysql,php和android studio插入服务器中,我可以作为localhost插入,但是当尝试在服务器中插入时却无法执行.我可以从数据库中查询信息,我拥有所有许可(表和行),并且它没有超出php文件中的连接限制,显然服务器或apache没有问题,所以我想知道是否可能是PHP文件或其他东西.任何帮助,将不胜感激!

Im creating an app, but i can't insert in a server using Mysql, php and android studio, i can insert as localhost, but when try to insert in the server it just doesn't do it. I can consult info from the data base, i have all the permitions (table and row), and it doesn't exceed the limit of conection in the php file, aparently there's no problem with the server or apache, so i wonder if might be the php file or something. Any help would be appreciated!

这是我用来上传信息的php文件.

this is the php file i used to upload the info.

<?php 

 //importing dbDetails file 
 require_once 'dbDetails.php';

 //this is our upload folder 
$upload_path = 'uploads/';

 //Getting the server ip 
 $server_ip = gethostbyname(gethostname());

 //creating the upload url 
 $upload_url = 'http://'.$server_ip.'/userapp/'.$upload_path; 

 //response array 
 $response = array(); 

 if($_SERVER['REQUEST_METHOD']=='POST'){

 //checking the required parameters from the request 
 if(isset($_POST['name']) and isset($_FILES['image']['name'])){

 //connecting to the database 
 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

 //getting name from the request 
 $name = $_POST['name'];
 $nombre = $_POST['nombre'];
 $apellido = $_POST['apellido'];
 $telefono = $_POST['telefono'];
 $categoria = $_POST['categoria'];
 $titulo = $_POST['titulo'];
 $descripcion = $_POST['descripcion'];
 $publico = $_POST['publico'];
 $terminos = $_POST['terminos'];
 $latitud = $_POST['latitud'];
 $longitud = $_POST['longitud'];

 //$mysqli_insert_id();
 //getting file info from the request 
 $fileinfo = pathinfo($_FILES['image']['name']);

 //getting the file extension 
 $extension = $fileinfo['extension'];

 //file url to store in the database 
 $file_url = $upload_url . getFileName() . '.' . $extension;

 //file path to upload in the server 
 $file_path = $upload_path . getFileName() . '.'. $extension; 

 //trying to save the file in the directory 
 try{
 //saving the file 
 move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
 $sql = "INSERT INTO `userapp`.`reportes2` (`id`, `url`,`campo_correo`,`campo_nombre`,`campo_apellido`,`campo_telefono`,`campo_categoria`,`campo_titulo`,`campo_descripcion`,`campo_publico`,`campo_terminos`,`campo_latitud`,`campo_longitud`)VALUES(NULL,'$file_url','$name','$nombre','$apellido','$telefono','$categoria','$titulo','$descripcion','$publico','$terminos','$latitud','$longitud');";

 //adding the path and name to database 
if(mysqli_query($con,$sql)){

 //filling response array with values 
 $response['error'] = false; 
 $response['url'] = $file_url; 
 $response['name'] = $name;
 }

 //////////////////////////////////////////////////////////
 //if some error occurred 
 }catch(Exception $e){
 $response['error']=true;
 $response['message']=$e->getMessage();
 } 
 //displaying the response 
 echo json_encode($response);

 //closing the connection 
 mysqli_close($con);
 }else{
 $response['error']=true;
 $response['message']='Please choose a file';
 }
 }

 /*
 We are generating the file name 
 so this method will return a file name for the image to be upload 
 */
 function getFileName(){
 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
 $sql = "SELECT max(id) as id FROM reportes2";
 $result = mysqli_fetch_array(mysqli_query($con,$sql));

 mysqli_close($con);
 if($result['id']==null)
 return 1; 
 else 
 return ++$result['id']; 
 } 

推荐答案

<?php

// Import db file.
require_once 'dbDetails.php';

// Upload folder.
$upload_path = 'uploads/';

// Get the server ip.
$server_ip = gethostbyname(gethostname());

// Create upload url.
$upload_url = 'http://' . $server_ip . '/userapp/' . $upload_path;

//response array 
$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Validate request parameters.
    if (isset($_POST['name']) and isset($_FILES['image']['name'])) {

        // Request values.
        $name = isset($_POST['name']) ? $_POST['name'] : '';

        //************************************************************************
        // NB: CHANGE IT TO A VALUE FROM THE FORM, OR DELETE IT FROM HERE AND SQL.
        // IF YOU DON'T INSERT THIS, THEN MAKE SURE THAT THE FIELD "campo_correo"
        // ACCEPTS NULL VALUES, OR GIVE IT A DEFAULT VALUE IN DB (LIKE THIS: '').
        $correo = isset($_POST['correo']) ? $_POST['correo'] : '';
        //************************************************************************

        $nombre = isset($_POST['nombre']) ? $_POST['nombre'] : '';
        $apellido = isset($_POST['apellido']) ? $_POST['apellido'] : '';
        $telefono = isset($_POST['telefono']) ? $_POST['telefono'] : '';
        $categoria = isset($_POST['categoria']) ? $_POST['categoria'] : '';
        $titulo = isset($_POST['titulo']) ? $_POST['titulo'] : '';
        $descripcion = isset($_POST['descripcion']) ? $_POST['descripcion'] : '';
        $publico = isset($_POST['publico']) ? $_POST['publico'] : '0';
        $terminos = isset($_POST['terminos']) ? $_POST['terminos'] : '0';
        $latitud = isset($_POST['latitud']) ? $_POST['latitud'] : '0';
        $longitud = isset($_POST['longitud']) ? $_POST['longitud'] : '0';

        // Get file info from request.
        $fileinfo = pathinfo($_FILES['image']['name']);

        // Get file extension.
        $extension = $fileinfo['extension'];

        // Build file url to insert in database.
        $file_url = $upload_url . getFileName() . '.' . $extension;

        // Build file path to upload to server.
        $file_path = $upload_path . getFileName() . '.' . $extension;

        try {
            // Save the file in the directory. 
            $movedUploadedFile = move_uploaded_file($_FILES['image']['tmp_name'], $file_path);
            if (!$movedUploadedFile) {
                throw new Exception('The file could not be moved.');
            }

            // Connect to database.
            $con = mysqli_connect(HOST, USER, PASS, DB);
            if (!$con) {
                throw new Exception('Could not connect to database');
            }

            // Insert record into table.
            $sql = "INSERT INTO `userapp`.`reportes2` (`url`, `name`, `campo_correo`, `campo_nombre`, `campo_apellido`, `campo_telefono`, `campo_categoria`, `campo_titulo`, `campo_descripcion`, `campo_publico`, `campo_terminos`, `campo_latitud`, `campo_longitud`) VALUES ('$file_url', '$name', '$correo', '$nombre', '$apellido', '$telefono', '$categoria', '$titulo', '$descripcion', '$publico', '$terminos', '$latitud', '$longitud')";

            $inserted = mysqli_query($con, $sql);
            if (!$inserted) {
                throw new Exception('The insert statement could not be executed!');
            }

            // Close the database connection.
            $closed = mysqli_close($con);
            if (!$closed) {
                throw new Exception('The database connection can not be closed!');
            }

            // Fill response array with values.
            $response['error'] = false;
            $response['url'] = $file_url;
            $response['name'] = $name;
        } catch (Exception $e) {
            $response['error'] = true;
            $response['message'] = $e->getMessage();
        }
    } else {
        $response['error'] = true;
        $response['message'] = 'Please choose a file.';
    }

    // Display response.
    echo json_encode($response);
} else {
    $response['error'] = true;
    $response['message'] = 'No post method used!';

    // Display response.
    echo json_encode($response);
}

/**
 * We are generating the file name, so this method will 
 * return a file name for the image to be upload.
 * 
 * @return int
 * @throws Exception
 */
function getFileName() {
    try {
        // Connect to database.
        $con = mysqli_connect(HOST, USER, PASS, DB);
        if (!$con) {
            throw new Exception('Could not connect to database!');
        }

        // Select max id.
        $sql = "SELECT max(id) as id FROM reportes2";
        $mysqliResult = mysqli_query($con, $sql);
        if (!$mysqliResult) {
            throw new Exception('The select statement failed!');
        }

        // Fetch max id.
        $result = mysqli_fetch_array($mysqliResult);

        // Close database connection.
        $closed = mysqli_close($con);
        if (!$closed) {
            throw new Exception('The database connection can not be closed!');
        }

        // Validate results.
        if ($result['id'] == null) {
            return 1;
        } else {
            return ++$result['id'];
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        exit();
    }
}


选项1:使用mysqli_stmt_get_result() + mysqli_fetch_array() :

Option 1: Using mysqli_stmt_get_result() + mysqli_fetch_array():

<?php

/*
 * Run prepared db queries.
 * 
 * Uses:
 *      - mysqli_prepare()
 *      - mysqli_stmt_bind_param()
 *      - mysqli_stmt_execute()
 *      - mysqli_stmt_get_result()
 *      - mysqli_fetch_array()
 */

try {
    $username = 'Hello';
    $password = 'World';

    //---------------------------------------------------------
    // Connect to db.
    //---------------------------------------------------------
    $conn = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
    if (!$conn) {
        throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
    }

    //---------------------------------------------------------
    // Sql statement.
    //---------------------------------------------------------
    $query = "SELECT * FROM users WHERE username = ? AND password = ?";

    //---------------------------------------------------------
    // Prepare sql statement.
    //---------------------------------------------------------
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        throw new Exception('The sql statement can not be prepared!');
    }

    //---------------------------------------------------------
    // Bind variables to the prepared statement as parameters.
    //---------------------------------------------------------
    $bound = mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
    if (!$bound) {
        throw new Exception('The variables could not be bound to the prepared statement!');
    }

    //---------------------------------------------------------
    // Execute the prepared statement.
    //---------------------------------------------------------
    $executed = mysqli_stmt_execute($stmt);
    if (!$executed) {
        throw new Exception('The prepared statement could not be executed!');
    }

    //---------------------------------------------------------
    // Get the result set from the prepared statement.
    //---------------------------------------------------------
    $result = mysqli_stmt_get_result($stmt);
    if (!$result) {
        throw new Exception(mysqli_error($conn));
    }

    //---------------------------------------------------------
    // Get the number of rows in statements result set.
    //---------------------------------------------------------
    $rows = mysqli_num_rows($result);

    if ($rows > 0) {
        //---------------------------------------------------------
        // Read the result set.
        //---------------------------------------------------------
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        if (!isset($row)) {
            echo 'No records returned!';
            exit();
        }

        echo 'Login successful: ' . $row['username'] . '/' . $row['password'];
    } else {
        echo 'Invalid username/password. Please check and retry login.';
    }

    //-----------------------------------------------------------
    // Frees stored result memory for the given statement handle.
    //-----------------------------------------------------------
    mysqli_stmt_free_result($stmt);

    //---------------------------------------------------------
    // Close db connection.
    //---------------------------------------------------------
    $closed = mysqli_close($conn);
    if (!$closed) {
        throw new Exception('The database connection can not be closed!');
    }
} catch (Exception $exception) {
    echo '<pre>' . print_r($exception, true) . '</pre>';
    exit();
}


选项2:使用mysqli_stmt_store_result() + mysqli_stmt_bind_result() + mysqli_stmt_fetch() :

Option 2: Using mysqli_stmt_store_result() + mysqli_stmt_bind_result() + mysqli_stmt_fetch():

<?php

/*
 * Run prepared db queries.
 * 
 * Uses:
 *      - mysqli_prepare()
 *      - mysqli_stmt_bind_param()
 *      - mysqli_stmt_execute()
 *      - mysqli_stmt_store_result()
 *      - mysqli_stmt_bind_result()
 *      - mysqli_stmt_fetch()
 */

try {
    $username = 'Hello';
    $password = 'World';

    //---------------------------------------------------------
    // Connect to db.
    //---------------------------------------------------------
    $conn = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
    if (!$conn) {
        throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
    }

    //---------------------------------------------------------
    // Sql statement.
    //---------------------------------------------------------
    $query = "SELECT * FROM users WHERE username = ? AND password = ?";

    //---------------------------------------------------------
    // Prepare sql statement.
    //---------------------------------------------------------
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        throw new Exception('The sql statement can not be prepared!');
    }

    //---------------------------------------------------------
    // Bind variables to the prepared statement as parameters.
    //---------------------------------------------------------
    $bound = mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
    if (!$bound) {
        throw new Exception('The variables could not be bound to the prepared statement!');
    }

    //---------------------------------------------------------
    // Execute the prepared statement.
    //---------------------------------------------------------
    $executed = mysqli_stmt_execute($stmt);
    if (!$executed) {
        throw new Exception('The prepared statement could not be executed!');
    }

    //---------------------------------------------------------
    // Transfer the result set from the prepared statement.
    //---------------------------------------------------------
    $stored = mysqli_stmt_store_result($stmt);
    if (!$stored) {
        throw new Exception('The result set from the prepared statement could not be transfered!');
    }

    //---------------------------------------------------------
    // Get the number of rows in statements' result set.
    //---------------------------------------------------------
    $rows = mysqli_stmt_num_rows($stmt);

    if ($rows > 0) {
        //---------------------------------------------------------
        // Bind result set columns to corresponding variables.
        //---------------------------------------------------------
        $bound = mysqli_stmt_bind_result($stmt, $resId, $resUsername, $resPassword);
        if (!$bound) {
            throw new Exception('The result set columns could not be bound to the variables');
        }

        //--------------------------------------------------------------------
        // Fetch results from the prepared statement into the bound variables.
        //--------------------------------------------------------------------
        while (mysqli_stmt_fetch($stmt)) {
            echo 'Successfully returned data:<br/><br/>';
            echo 'ID: ' . $resId . '<br/>';
            echo 'Username: ' . $resUsername . '<br/>';
            echo 'Password: ' . $resPassword . '<br/>';
        }
    } else {
        echo 'Invalid username/password. Please check and retry login!';
    }

    //-----------------------------------------------------------
    // Free stored result memory for the given statement handle.
    //-----------------------------------------------------------
    mysqli_stmt_free_result($stmt);

    //---------------------------------------------------------
    // Close db connection.
    //---------------------------------------------------------
    $closed = mysqli_close($conn);
    if (!$closed) {
        throw new Exception('The database connection can not be closed!');
    }
} catch (Exception $exception) {
    echo '<pre>' . print_r($exception, true) . '</pre>';
    exit();
}


Nota bene: 尝试将mysqli_stmt_store_result()mysqli_stmt_get_result()一起使用会导致错误.


Nota bene: Trying to use mysqli_stmt_store_result() together with mysqli_stmt_get_result() will lead to errors.

这篇关于无法在服务器中插入信息,但我可以作为本地主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆