简体   繁体   中英

having problems to execute a PHP code with simple mySQL query

I am trying to execute a query with a WHERE clause but it looks like the id I retrieve needs to be perhaps converted from an array into something else. I am new to PHP so I am struggling a little:

...some previous query here
$sharepoint_id = $data[0];
//returns Array([ID] => a5f415a7-3d4f-11e5-b52f-b82a72d52c35)   

qry = mysql_query("SELECT HostName FROM MSSWireList WHERE id=".$sharepoint_id);     
    $data = array();
    while($rows = mysql_fetch_array($qry))
    {
        $data[] = array(
                    "ID"          => $rows['ID'],
                    "Record"      => $rows['Record'],                                
                    "HostName"    => $rows['HostName']
                    );
    }
    return json_encode($data);  

also tried $sharepoint_id = $data[0]->ID; Thank you

"returns Array([ID] => a5f415a7-3d4f-11e5-b52f-b82a72d52c35)"

That's a string and not an integer. The variable in your WHERE clause needs to be quoted.

WHERE id='".$sharepoint_id."' ");

Checking for errors would have signaled the syntax error.

Add or die(mysql_error()) to mysql_query() .


Your present code is open to SQL injection . Use mysqli_* with prepared statements , or PDO with prepared statements .


Edit:

You only selected the HostName column from your query and not the other two, ID and Record .

However, when going over a loop, row names are case-sensitive.

So, if your row's case is id as opposed to ID , then that will matter in your loop.

  • $rows['ID'] and $rows['id'] are two different animals.

Sidenote:

Pulled from a comment I asked already:

qry = mysql_query if that your real code, it's missing a $ for qry .

And if so, error reporting would have thrown you an undefined constant qry notice.

I won't take you to task for using the old mysql driver instead of mysqli or PDO, or for not using a prepared statement - I'll leave that for others to do - but

"...WHERE id = '" . $sharepoint_id['ID'] . "'"

should do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM