开发者

PHP/MYSQL: getting value from primary column

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 record开发者_开发问答s 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.


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


Is column id a string type or integer type? If it is an integer, you should take the single quotes out of the query string. That might be your problem.


$sql='SELECT * FROM member WHERE id=' . intval($userId);


The return only being {} tells me that your loop is never even executing so it is not finding any results. Id try echoing out your $sql variable and copy/paste it into your sql and see what it spits out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜