将Android连接到MySQL

时间:2015-03-17 09:35:09

标签: php android mysql

所以我对此非常陌生。 我在Android Studio中修改了新项目的代码以使用webview类处理HTML5,我用phpmyadmin创建了一个数据库,我创建了一个搜索引擎php来从数据库中检索数据。 我的项目实际上是关于将android应用程序与数据库连接,数据库包含目录等产品列表,最后它必须能够单独检索每条记录并允许用户反馈。尽管如此,我还不知道如何使用我之前创建的所有php代码(带有修改或其他内容)将android应用程序与数据库连接起来。正如我所说的,我对这一切都是新手,所以我不知道是否使用webview带来用php创建的搜索应用程序在android应用程序项目中可以被认为是正确的,这是学校项目中的重要因素。 / p>

非常感谢您提供的任何意见或帮助。

编辑* 现在我有了这个:

<?php 

$server = "localhost";
$user = "root";
$pass = "XXX";
$bd = "XXX";


$conexion = mysqli_connect($server, $user, $pass,$bd) 
or die("Ha sucedido un error inexperado en la conexion de la base de datos");


$input=$_REQUEST['input'];

$sql="SELECT * FROM registres where id=".$input;
mysqli_set_charset($conexion, "utf8"); //formato de datos utf8

if(!$result = mysqli_query($conexion, $sql)) die();

$registres = array(); 

while($row = mysqli_fetch_array($result)) 
{ 
    $id=$row['id'];
    $isbn=$row['ISBN'];
    $titol=$row['titol'];
    $autor=$row['autor'];
    $any=$row['any'];
    $descripcio=$row['descripcio'];
    $format=$row['format'];

    $registres[] = array('id'=> $id, 'ISBN'=> $isbn, 'titol'=> $titol, 'autor'=> $autor, 'any'=> $any, 'descripcio'=> $descripcio, 'format'=> $format);

}

//desconectamos la base de datos
$close = mysqli_close($conexion) 
or die("Ha sucedido un error inexperado en la desconexion de la base de datos");


$json_string = json_encode($registres);
echo $json_string;



?>

但是系统会返回以下内容:

注意:未定义的索引:在第13行的E:\ xampp \ htdocs \ json4 \ api \ api3.php中输入

谢谢!

2 个答案:

答案 0 :(得分:0)

您无法在WebView中运行PHP代码。但你可以使用HTML5和Javascript。要连接数据库,

  1. 首先你需要创建API,为此创建一个名为search.php的页面并将其托管给你的服务器,例如。 www.yourdomain.com/search.php
  2. 现在编码search.php连接数据库并从mysql获取结果,将它们存储在数组中,最后输出为JSON
  3. 的search.php

    <?php
    $con=mysql_connect(host,user,pass);
    $input=$_REQUEST['input'];
    
    $sql="select * from table where field=".$input; //change table and field
    
    $result=mysql_query($sql,$con);
    
    $rows=array();
    
    while($row=mysql_fetch_array($result)){
        $rows[]=$row;
    }
    
    echo json_encode($rows); //it outputs results as JSON
    ?>
    

    //现在您的Android应用程序可以使用javascript来使用AJAX来对URL发出请求,使用JQUERY Mobile进行简单的AJAX调用 www.yourdomain.com/search.php?input=some+text

    和AJAX调用返回可以在webview中解析和显示的JSON数据。

答案 1 :(得分:0)

希望你不要这样做。 Sqlite是Android推荐的数据库。所以不要尝试使用其他数据库。所有其他对Android来说太沉重了。