Note that there are some explanatory texts on larger screens.

plurals
  1. POPhp Script only returning last value
    text
    copied!<p>Hey I have the following script that is not working and its getting late for me so I could use some help. This receives an array of id's from an http post and is supposed to grab the user names. When sending it a single Id which I know is in my database I get null back. Whats wrong with my script?</p> <pre><code>&lt;?php $friendArray[] = $_POST["friendId"]; $hostname = 'http://localhost/'; $dbname = 'MYDB'; $db_username = 'user'; $db_password = 'pass'; $options = array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8', ); $inQuery = implode(',', array_fill(0, count($friendArray), '?')); try { $dsn = "mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=".$dbname; $dbh = new PDO( $dsn, $db_username, $db_password, $options); $dbh-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false ); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $dbh-&gt;prepare('SELECT USER_SCREEN_NAME USER WHERE USER_ID IN (' . $inQuery . ')'); foreach ($friendArray[] as $k =&gt; $friend) { $sth-&gt;bindValue(($k+1), $friend); } $sth-&gt;execute(); $results = $sth-&gt;fetchAll(PDO::FETCH_ASSOC); $json=json_encode($results); echo $json; } catch(PDOException $e) { echo $e-&gt;getMessage(); } $dbh = null; ?&gt; </code></pre> <p>Solution: The main problem I found was there was no "FROM" in the sql statement. After that I went through a bunch more iterations and problems finally getting to the following which worked. Another issue was that looping and binding was not working, so once I got the array in the proper format passing it in execute did the trick.</p> <pre><code>&lt;?php $friendArray = array(); foreach ($_POST["friendId"] as $myFriend) { $friendArray[] = $myFriend; } $hostname = 'http://localhost/'; $dbname = 'MYDB'; $db_username = 'user'; $db_password = 'pass'; $options = array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8', ); $inQuery = implode('', array_fill(0, count($friendArray)-1, " OR USER_ID = ?")); try { $dsn = "mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=".$dbname; $dbh = new PDO( $dsn, $db_username, $db_password, $options); $dbh-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false ); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $dbh-&gt;prepare("SELECT USER_SCREEN_NAME FROM USER WHERE USER_ID = ?" . $inQuery . ""); $sth-&gt;execute($friendArray); $results = $sth-&gt;fetchAll(PDO::FETCH_ASSOC); $json=json_encode($results); echo $json; } catch(PDOException $e) { echo $e-&gt;getMessage(); } $dbh = null; ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload