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?
Related
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.
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Closed 6 years ago.
I am trying for getting multiple records from database but when I try for more then one records. I always getting empty.
First I try FROM DbOperation.php:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT DateString FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
php data get
<?php
require_once 'DbOperation.php';
$db = new DbOperation();
$DateString = $_POST['DateString'];
$devices = $db->getDayListByDate($DateString);
$response = array();
$response['error'] = false;
$response['devices'] = array();
while($device = $devices->fetch_assoc()){
$temp = array();
$temp['Question']=$device['Question'];
$temp['Option_2']=$device['DateString'];
array_push($response['devices'],$temp);
}
echo json_encode($response);
Response: {"error":false,"devices":[{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}]}
But when I trying for all records and change database query for getting Question field in reponse like.
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
I am getting result empty like "".
I am using for connection
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Config.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
I think the way you are binding is incorrect too:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= :DS");
$stmt->bind_param(":DS",$DateString);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
Try This
function getDayListByDate($DateString) {
$result = $this->con->query("SELECT * FROM gk_eng WHERE DateString='$DateString' ");
return $result;
}
you can get answer.. if didnt get ans .. let me know
Actually, I connected to 3 databases in different server, but I got problem in mysqli_query.
sometimes it worked fluently without any error, but sometimes it showed "PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result"..
I don't know what happen, it ocurred sometimes.
here is my connection :
connection.php
<?php
$DatabaseName1 = "db_name1";
$DbHostName1 = "host1";
$DbUserName1 = "username";
$DbPassWord1 = "password";
$DatabaseName2q = "db_name2";
$DbHostName2 = "host2";
$DbUserName2 = "username2";
$DbPassWord2 = "password2";
$DatabaseName3q = "db_name3";
$DbHostName3 = "host3";
$DbUserName3 = "username3";
$DbPassWord3 = "password3";
$mysqli1 = mysqli_connect("$DbHostName1", "$DbUserName1", "$DbPassWord1", "$DatabaseName1");
$mysqli2 = mysqli_connect("$DbHostName2", "$DbUserName2", "$DbPassWord2", "$DatabaseName2q");
$mysqli3 = mysqli_connect("$DbHostName3", "$DbUserName3", "$DbPassWord3", "$DatabaseName3q");
$server[1] = $mysqli1;
$server[2] = $mysqli2;
$server[3] = $mysqli3;
$count_db = 3;
if(!$mysqli1){
echo "error to connect server 1st";
die();
}
if(!$mysqli2){
echo "error to connect server 2nd";
die();
}
if(!$mysqli3){
echo "error to connect server 3rd";
die();
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
task1.php
<?php
include("connection.php")
for($i=1;$i<=$count_db;$i++){
$conn = $server[$i];
$array = mysqli_fetch_array(mysqli_query($conn,"select * from `table`"));
$task = $array["field"];
}
?>
anyone guys can help?
Do it like this
for($i=1;$i<=$count_db;$i++){
$conn = $server[$i];
$resultset = mysqli_query($conn,"select * from `table`")
if(!$resultset){
//do something
continue; //if you don't want to break it
}
$array = mysqli_fetch_array($resultset);
$task = $array["field"];
}
I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);
I am working with a MySQL Database and having some issues while trying to get data from several built-in PHP MySQL methods. I have written a class to interact with the database, and here are the relevant bits:
<?php
include("includes/Config.inc.php");
include_once("ChromePHP.class.php");
class Database{
private $db;
private $hostname;
private $username;
private $password;
private $schema;
function __construct() {
if(func_num_args() == 0){
$this->hostname = conf_hostname;
$this->username = conf_username;
$this->password = conf_password;
$this->schema = conf_schema;
}
else{
$params = func_get_args();
$this->hostname = $params[0];
$this->username = $params[1];
$this->password = $params[2];
$this->schema = $params[3];
}
$this->open();
}
private function open(){
$this->db = mysql_connect($this->hostname, $this->username, $this->password) or die ('Error connecting to mysql');
mysql_select_db($this->schema, $this->db);
mysql_query("SET NAMES utf8");
}
public function executeQuery($query){
$results = mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
return $results;
}
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$bits = explode(' ', $info);
return $bits[4];
}
return false;
}
public function close(){
mysql_close($this->db);
}
public function escape($string){
$output = mysql_real_escape_string($string , $this->db);
return $output;
}
public function getRegionTree(){
$query = "SELECT COUNT(parent.Name) - 2 as level, node.Name AS Name, node.ID, node.Parent
FROM Region AS node, Region AS parent
WHERE node.LeftVal BETWEEN parent.LeftVal AND parent.RightVal and node.Name <> 'Earth'
GROUP BY node.ID
ORDER BY node.LeftVal";
$result = $this->executeQuery($query);
$last_level = 0;
$output = '<ul id="regionTree">'.PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
$link = '<li>'.PHP_EOL.''.$row["Name"]."".PHP_EOL;
$diff = $last_level - $row["level"];
if($diff == 0){
// Sibling
$output .= ($row["level"] != 0) ? '</li>'.PHP_EOL.$link:$link;
}
elseif($diff < 0){
// Child
$demoter = '<ul>'.PHP_EOL;
for ($i=0; $i > $diff; $i--) {
$output .= $demoter;
}
$output .= $link;
}
else{
// Parent
$promoter = '</li>'.PHP_EOL.'</ul>';
for ($i=0; $i < $diff; $i++) {
$output .= ($row["level"] != 0) ? $promoter.PHP_EOL."</li>":$promoter;
}
$output .= $link;
}
$last_level = $row["level"];
}
$output .= "</li></ul>";
return $output;
}
public function addRegion($name, $type, $parentID){
$query = "select Name, Region_Type from Region where ID = ".$parentID;
$result = $this->executeQuery($query);
if($result){
$row = mysql_fetch_assoc($result);
$query = "call AddRegion('".$name."', '".$type."', '".$row["Name"]."', '".$row["Region_Type"]."', #returnCode, #returnMessage)";
$result = $this->executeQuery($query);
if($result){
return true;
}
else{
$query = "select #returnCode as code, #returnMessage as message";
$result = $this->executeQuery($query);
while($row = mysql_fetch_assoc($result)){
print_r($row);
}
return false;
}
}
return false;
}
public function getInfo(){
return mysql_info();
}
public function editRegion($id, $name, $type){
$query = "update Region set Name = '$name', Region_Type = '$type' where ID = $id";
if($this->executeNonQuery($query) > 0){
return true;
}
return false;
}
}
$db = new Database();
?>
With this Database class I am able to successfully make queries, get region trees, and successfully change data in the database using the ExecuteNonQuery function. However, any attempts I have made to use mysql_info, mysql_affected_rows, or other similar functions fails, making it really difficult to write any error handling code. To make matters stranger yet, if I run the following code:
<?php
$db = mysql_connect("localhost", "User", "Password") or die ('Error connecting to mysql');
mysql_select_db("DB", $db);
mysql_query("update Region set Name = 'test' where ID = 594", $db);
echo mysql_info($db);
?>
I am able to get results as expected. Any Ideas?
Are you using mysql_info and mysql_error outside the Database class? And if so how are you referencing the database connection? If you don't identify the database connection then:
The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING
level error is generated.
So internally you should be doing mysql_info($this->db); to get mysql_info. Accessing $db externally requires you to write something to get around it being private.
But if you are going to be doing database stuff in an object-oriented mode you really should investigate PDO.
After adding "or die()" statements in several places in my script, I was surprised to see that nothing was actually failing to work, instead it was failing to work the way I expected it to. The problem I was having as it turns out, was that splitting the output of mysql_info (on the space character) resulted in several indices in the array containing nothing, as would be generated by inconsistent whitespace in the output of mysql_info. The index that I thought (based upon counting spaces visually) would contain an integer instead contained a string, and I was attempting to compare that string against the number 0, which won't work. I have updated my executeNonQuery function as follows:
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$output = array();
$bits = explode(' ', $info);
$output["rowsMatched"] = $bits[2];
$output["rowsChanged"] = $bits[5];
$output["warnings"] = $bits[8];
return $output;
}
return false;
}