Adapting an answer from here to try and pass an array as the parameter for a WHERE clause in MySQL. Syntax seems okay but I'm just getting null back form the corresponding JSON. I think understand what it is supposed to do, but not enough that I can work out where it could be going wrong. The code for the function is;
public function getTheseModulesById($moduleids) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$in = join(',', array_fill(0, count($moduleids), '?'));
$select = "SELECT * FROM modules WHERE id IN ($in)";
$statement = $con->prepare($select);
$statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
$statement->execute();
$result = $statement->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
mysqli_close($con);
return $arr;
}
And the code outwith the function calling it looks like;
$id = $_POST['id'];
$player = $db->getPlayerDetails($id);
if ($player != false) {
$pid = $player["id"];
$moduleids = $db->getModulesByPlayerId($pid); //this one is okay
$modules = $db->getTheseModulesById($moduleids); //problem here
$response["player"]["id"] = $pid;
$response["player"]["fname"] = $player["fname"];
$response["player"]["sname"] = $player["sname"];
$response["modules"] = $modules;
echo json_encode($response);
[EDIT]
I should say, the moduleids are strings.
Related
I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.
I want to give out a for every line in my database.
It seems that it is working but only returns the first column.
Note: There are values for the empty fields in database!
$columns = "Ticket, Last_Modified_Date, Requester";
Heres my code:
function getTicket($columns){
echo($columns);
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns);
foreach($rows as $row){
echo("<tr>");
foreach($col_names as $col_name){
if (!isset($row[$col_name])){
continue;
}
echo("<td>".$row[$col_name]."</td>");
}
echo("</tr>");
}
}
else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}
->fetch() returns only one value of the rows.
Use ->fetchAll() ( PHP Documentation ) if you want to return all of your results.
There are a couple of issues here, first you should use ->fetchall() which will return ALL the result rows in one hit into an array.
Second you are overwriting your $result statement handle with the row being returned by ->fetch
function getTicket($columns){
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
// CHANGES HERE
$rows = $result->fetchall(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns); //make array of csv
foreach($rows as $row){
foreach( $col_names as $col_name ) {
echo '<td>' . $row[$col_name] . '</td>';
}
}
}else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}
I have this seriously strange issue. I have 4 tables in a FileMaker 12 file: Issues, Articles, FMBM, Ads. I have 2 methods in my results class, one writes a series of serial IDs to each of these tables, the other queries those tables. The method that writes the serial ID's works perfectly. The method that queries the tables works for 3 of the 4 tables (Articles, FMBM, Ads) but returns no result set for Issues.
I have checked permissions, but as this is the admin user, it has full access to all and there are no table specific or layout specific restrictions (again, it's the admin). Oddly enough, I thought maybe it's the query, but when I run "SELECT * FROM Issues" in my ODBC Query Tool, it returns the appropriate results. It's just baffling to me that the setKeys() method works perfectly but the view method ONLY fails on Issues.
The Model:
class Application_Model_Results {
public $keys;
public $odbc;
public $comp = array('Issues', 'Articles', 'Ads', 'FMBM');
public $existing = array();
function setKeys() {
$this->odbc = 'Migrator';
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
foreach ($this->comp as $c) {
$sql = "SELECT Serial_ID FROM " . $c;
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
while (odbc_fetch_row($rs)) {
$this->existing[] = odbc_result($rs, 'Serial_ID');
}
if (in_array(true, $this->keys[$c])) {
foreach ($this->keys[$c] as $v) {
if (!in_array($v, $this->existing)) {
$iSql = "INSERT INTO " . $c . "(Serial_ID) VALUES('$v')";
odbc_exec($conn, $iSql);
$obj->output = 'Inserted Serial_ID: ' . $v . ' into table ' . $c;
$obj->logger();
}
}
}
}
}
public function getResults($table) {
$this->odbc = 'Migrator';
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
$sql = "SELECT * FROM " . $table;
$rs = odbc_exec($conn, $sql);
while (odbc_fetch_row($rs)) {
$results[odbc_result($rs, 'Serial_ID')] = odbc_fetch_array($rs);
}
return $results;
}
}
The Controller:
public function viewAction()
{
$results = new Application_Model_Results();
$result = $results->getResults('Issues');
$page = $this->_getParam('page', 1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(1);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;
}
Note: If scrap the view code, and just write:
<?php
$conn = odbc_connect('Migrator', 'admin', '********');
$sql = "SELECT * FROM Issues";
$rs = odbc_exec($conn, $sql);
while(odbc_fetch_row($rs)){
print_r(odbc_result_all($rs));
}
I get no rows returned.
EDIT:
Culprit has been found:
while (odbc_fetch_row($rs)) {
$results[odbc_result($rs, 'Serial_ID')] = odbc_fetch_array($rs);
}
Now, I am working on a solution that grabs each result row and pushes it to an associative array, the problem is, on the view, I need to dump everything, not have to use odbc_result($rs, ) for every single field.
Finally, my nightmare is over:
public function getResults($table) {
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
$sql = "SELECT * FROM " . $table;
$obj->output = 'Running query: ' . $sql;
$obj->logger();
$rs = odbc_exec($conn, $sql);
$obj->output = 'Results found: ' . odbc_num_rows($rs);
$obj->logger();
$results = array();
$i = 1;
while(odbc_fetch_row($rs)){
$results[] = odbc_fetch_array($rs, $i);
$i++;
}
return $results;
}
This returns an associative array that I can actually loop through.
NOTE: in this instance, any use of odbc_fetch_array, odbc_fetch_object, odbc_fetch_into, unless I forced the odbc_fetch_array to have a row value, would only reutrn every other result, not all results and then would die on the view unless I specifically called for a field value, and even then, the same value persisted across all paginated records.
i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
In db.php I have:
<?php
class connect {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $database = "databasename";
private $connect = null;
function connect() {
$this->connect = mysql_connect($this->host, $this->user, $this->pass) or die("Can't connect database");
mysql_select_db($this->database, $this->connect);
}
function getData() {
$data = array();
$sql = 'Select * From test';
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
$data[] = array($row['id'], $row['name']);
}
return $data;
}
}
?>
In index.php I have:
<?php
include 'db.php';
$connect = new connect();
$connect->connect();
$data = $connect->getData();
$str = '';
foreach ($data as $dt) {
$str .= $dt[1];
}
echo $str;
?>
I am getting the following error:
=> error: <b>Warning</b>: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource from db.php.
What am I doing wrong?
Try to find what is the error:
function getData() {
$data = array();
$sql = 'Select * From test';
$query = mysql_query($sql);
if(!$query)
{
echo 'Error: ' . mysql_error(); /* Check what is the error and print it */
exit;
}
while($row = mysql_fetch_array($query)) { /* Better use fetch array instead */
$data[] = array($row['id'], $row['name']);
}
return $data;
}
That error is telling you that your query executed by $query = mysql_query($sql); is returning an error. It's not returning zero results, it's returning an error which suggests that your database named 'databasename' or table within that named 'test' doesn't exist.
It sounds like no results are returned from the query or a general query error, do the columns and table in the query exist and is your connection to the database all okay?