我正在创建一个应用程序,但我无法使用Mysql,php和android studio插入服务器,我可以作为本地主机插入,但是当尝试插入服务器时,它就是不这样做。我可以从数据库中查询信息,我有所有的许可(表和行),并且它不超过 php 文件中的连接限制,当然服务器或 apache 没有问题,所以我想知道可能是 php 文件或其他东西。任何帮助将不胜感激!
这是我用来上传信息的PHP文件。
<?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'];
}
编辑 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();
}
}
编辑 2 - 如何使用 mysqli 库准备和运行查询:
选项 1:使用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()
:
<?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();
}
注意:尝试将mysqli_stmt_store_result()
与mysqli_stmt_get_result()
一起使用会导致错误。