dongtun2572 2014-05-14 09:34
浏览 36
已采纳

PHP:从数据库返回JSON内容而不是String

I would like to return a JSON objet containing informations retrieved from my database. Today, i only check that the username/password couple is correct and return a string "success".

The structure of tbl_user table is the following :

================================
============ tbl_user ==========
================================
- id
- username
- password
- name
- surname
- city
================================
================================

If the username/password couple exist in database, i would like to return a JSON object like that :

{
   username : ..,
   name : ..,
   surname : ..,
   city : ..
}

How can i do this ?

Here is my PHP code :

<?php
$hostname_localhost ="localhost";
$database_localhost ="database";
$username_localhost ="myusername";
$password_localhost ="mypassword";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
 if($rows == 0) { 
 echo "fail"; 
 }
 else  {
    echo "success"; 
}
?>
  • 写回答

3条回答 默认 最新

  • donglu3243 2014-05-14 09:39
    关注

    First alter your select statement:

    select field1, field2, ... from tbl_user where username = ....
    

    then:

    $rows = mysql_fetch_assoc($query_exec);
    
    // you will get JSON data of all fields used in your selection
    $jsonData = json_encode($rows);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析