0

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!

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']; 
 } 
  • You said that it works on the localhost but it is not working on the server !! so what errors are getting ? – lotfio May 15 '17 at 22:14
  • @aendeerei hahahalet hope this time it works! im crossing my fingers! :) – Danniel Prado Jun 05 '17 at 10:23
  • @aendeerei ok do you want me to test it with tha app in the cellphone? – Danniel Prado Jun 05 '17 at 10:26
  • @aendeerei MAAAAAAAAAN!!! what can i say? i think now im the one who's gonna cry!! gosh i can't belive it. MAN It works!! you did it!!! Thanks so MUCH! – Danniel Prado Jun 05 '17 at 10:30
  • @aendeerei hello buddy! Thanks to YOU for the time, effort, your time, your sleep and patience, seriously! hey if i have more questions in the future can i ask for your help? – Danniel Prado Jun 05 '17 at 10:37
  • @aendeerei ok, no prob. tell me. – Danniel Prado Jun 05 '17 at 10:37
  • @aendeerei : ), i reallyapreciate it! and whats recommendations and things to do i better do. – Danniel Prado Jun 05 '17 at 10:40
  • @DannielPrado Ok. So: you go in your db table and make the following: (1) In the configs, give default values to the fields which you don't want to allow NULL values. (2) Set "allow NULL" to the fields you want to accept NULL values. (3) I gave default values (like for latitud I gave '0') in the PHP code. Please change that properly after you make the config cahnges in db. –  Jun 05 '17 at 10:43
  • @DannielPrado Than all errors like `Field 'name' doesn't have a default value` disapear. –  Jun 05 '17 at 10:44
  • @DannielPrado The BIG KEY for your problem was this line: `if (!$inserted) { throw new Exception('The insert statement could not be executed. ' . mysqli_errno($con) . ' - ' . mysqli_error($con) . ' - ' . mysqli_error_list($con) . ' - ' . mysqli_warning_count($con)); }`. COPY IT AND USE IT ONLY ON DEVELOPMENT SERVER. Only this `mysqli_[...]` functions were able to display the warnings/errors. –  Jun 05 '17 at 10:47
  • Please don't use the comments section for extended conversation; we have the chat area for that. Comments can be deleted at any time, so all valuable information in them will be lost. It's best to use chat to discuss and then update the answer will all relevant information. – Modus Tollens Jun 05 '17 at 10:47
  • @aendeerei in the app i have validations in all the fields, because it is suppossed that you have to fill all the fields and so you don't have any NULL values. and about the the latitude and longitude, it's the same you cant push the send button if you don't move a marker it doesn't allow you to send any information. Do you think thins might be enough? or should i change anything else my friend? – Danniel Prado Jun 05 '17 at 10:48
  • @DannielPrado Yes, you need to change your perspective from now on: Never trust what users post to server and never trust client side functions and functionalities. ALWAYS make the proper validations on the server side, even if you made them on client side. –  Jun 05 '17 at 10:53
  • @aendeerei Ok, im going to make the changes that you told me, you're right, even with those validations, i should not trust the information people can put. – Danniel Prado Jun 05 '17 at 10:55
  • @DannielPrado You should read about "SQL injection". And, the most important thing: use PREPARED STATEMENTS! I'll give you 2 files with codes for that. Not right now but soon. –  Jun 05 '17 at 10:56
  • @aendeerei ok buddy i'd aprecciate that a lot, and thank you SO MUCH for your advices. you saved my life! – Danniel Prado Jun 05 '17 at 10:58
  • @aendeerei ok, to me is Perfect buddy! – Danniel Prado Jun 05 '17 at 10:58
  • @DannielPrado Then, Apache have error logs. PHP have error logs, MySQL have error logs. Searh them and remember their paths. They are very very important for development. –  Jun 05 '17 at 10:59
  • @aendeerei perfect, i will. i mean you told me to do that first in one of your first comments, but i didn't do that good at searching and interpretating them. – Danniel Prado Jun 05 '17 at 11:01
  • @DannielPrado As I saw your code is pretty clean. Read this also: [Quality code](https://www.butterfly.com.au/blog/website-development/clean-high-quality-code-a-guide-on-how-to-become-a-better-programmer). –  Jun 05 '17 at 11:02
  • @aendeerei ok i will. thank you my friend! – Danniel Prado Jun 05 '17 at 11:03
  • @DannielPrado No problem, from now you know that they need to be found :-) And, if you have free time start learning OOP. And use PDO instead of mysqli. –  Jun 05 '17 at 11:04
  • @aendeerei ok i think i need to read about differen topics. thank so much buddy for all your advices, and your time AGAIN! – Danniel Prado Jun 05 '17 at 11:05
  • @aendeerei ok buddy i think it's to for us to sleep. thanks for the wishes and you're a really nice and kind person. i wish you the same as well i bet you are going to get anything you want because of your way of being. Have a great night/day. See you!! : ) – Danniel Prado Jun 05 '17 at 11:11
  • @aendeerei i'm god man, how about you? Oh thank you so much. Hugs : ) – Danniel Prado Jun 08 '17 at 00:15
  • @DannielPrado I'm good, thanks. Just helping someone. Probably another 10 hours editing and testing :-))))) You are welcome. Ciao. –  Jun 08 '17 at 00:23
  • @aendeerei woow, Are you serious? you're awesome man. i'm glad you're doing good. :) – Danniel Prado Jun 08 '17 at 00:43
  • @DannielPrado I'm having fun doing it, so... :-) Bye and have a good time. –  Jun 08 '17 at 01:25
  • @DannielPrado Hello my friend, how are you doing? In June you were using mysqli. If you decided to use PDO in the mean time (as I also recommend you), then look into [this answer of mine](https://stackoverflow.com/questions/46014772/return-multiple-response-data-in-one-response/46018999#46018999) (in the "EDIT" part). There is a class I developed, which you'll certainly need and like to use. Have fun ;-) Bye –  Sep 03 '17 at 16:24

1 Answers1

1

EDIT 1:

<?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();
    }
}



EDIT 2 - How to prepare and run queries using mysqli library:


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();
}


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: Trying to use mysqli_stmt_store_result() together with mysqli_stmt_get_result() will lead to errors.