douzhang2680 2011-02-25 00:27
浏览 21
已采纳

PHP / MYSQL:从主列获取值

I have a script where I am just trying to return information when I send in an id via ajax to a php script, query the DB and return the name associated with the id.

Here is the php:

$userId = $_REQUEST['id'];
// Make a MySQL Connection
require('/php/dbconnect.php');

$sql="SELECT * FROM member WHERE id='".$userId."'";

$result = mysql_query($sql) or die(mysql_error());
$returnJson = '{';
while ($row = mysql_fetch_array($result)) {
    $returnJson .= 'userName: "' . $row['userName'] . '"';
}

$returnJson .= '}';
echo $returnJson;

I have 2 records in the member table. The primary id's are 1 and 2. When I request this page via ajax and pass in either 1 or 2 as parameter "id" I don't get the name back.

All that is returned is "{}";

I know that everything is working on the front-end because I get atleast get "{}" back.

I have checked that there is a column named "userName" in the DB. I also know that my connection to the DB works as no mysql errors return, and (using the same db connect script) I can write to the member table just fine.

Any ideas why this is not returning anything.

  • 写回答

4条回答 默认 最新

  • dsbfbz75185 2011-02-25 00:32
    关注

    3 things:

    1. Don't use request. Use $_GET or $_POST
    2. NeverNEVERNVNERNVNER put a variable right into an sql statement like that. If you arent going to use PDO and prepared statements make sure you escape your variables
    3. And the part that might be the answer... Try not putting quotes around the variable, i believe in the newer versions of mysql you can but in the older versions if you put quotes around something that was an integer field it wouldnt run correctly.

      $sql="SELECT * FROM member WHERE id=" . mysql_real_escape_string($userId);
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)