I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];
Related
When using this PHP code
$random = 00000; //a random int
$gameCode = $random;
$players = 0; //An example number
echo "<h4>$players Players</h4>";
while(true) {
sleep(1);
$sql = "SELECT id FROM gamecode WHERE gamecode = '$gameCode'";
$result = $conn->query($sql);
if ($result->num_rows != $players) {
$players = $result->num_rows;
echo "<h4>$players Players</h4>";
flush();
}
}
I am 99% the variables cant be found as i get an error saying that it is not an object and it works when i define the variable in the while loop. (Which i cant do for reasons)
Notice: Trying to get property of non-object in /storage/ssd4/654/2919654/public_html/createcode.php on line (Lines trying to use $players and $gamecode)
Thanks
The only thing that should be an object in there is $result, I expect that the query has failed and $result == false
When you call $result->num_rows that will fail with the error message you are seeing.
Try adding this test in
$result = $conn->query($sql);
if (!$result) {
die('Something broke');
}
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
I'm not really much into PHP or mySQL so I hope you can help me.
I got a php script with a function that returns a json with all the entries in a database table:
public function select($table, $wheres = null)
{
$connect = $this->connect();
if ($wheres == null)
{
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'`');
} else {
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'` WHERE '.$this->wheres($wheres));
}
$i = 0;
$ret = array();
while ($row = mysqli_fetch_assoc($query)) {
foreach ($row as $key => $value) {
$ret[$i][$key] = $value;
}
$i++;
}
return ($ret);
}
Edit:
I have my application which calls this function. Everything worked as expected but then I added 2 more fields to one of the tables ( 1 text, 1 varchar ), and now when I call this function it returns nothing ; literally an empty string.
I've also noticed that if I just delete those new fields it works, which is kinda annoying plus I need those fields and I can't figure out where the problem root is.
Also, the application code is not the problem: when this function is called it only passes 2 parameters (the method name, and the table name), it can't be wrong.
By the way, here is the table structure if it may help you help me:
pic related
This function helps you to get data form database in json from , this return json
<?php
function getData($tbl_name=null,$id=null)
{
$con = mysqli_connect("localhost","root","","mydb"); //my db is my database name
if(!$con){ die( "could't connect with database" ); }
$sql = mysqli_query($con,'SELECT * FROM $tbl_name WHERE id = {"$id"}');
while($row = mysqli_fetch_assoc($sql))
{
#echo"<pre>";
#print_r($row); //this will return data form data base in array from
return json_encode($row);
}
}
?>
These lines are from a php function on a web server, the client is an ios app,
I get an error on the result2 query
$result = query("SELECT field1 FROM table1 WHERE field2='%s' limit 1", $value);
$row = mysql_fetch_array($result);
$result2 = query("SELECT field2 FROM table1 WHERE field3='%s' limit 1", $row['field1']);
on Xcode I get the error (in json):
{
error = "The operation couldn't be completed. (Cocoa error 3840.)";
}
here is the definition of the function query
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
what's wrong with that query?
thanks
You are using mysqli_ functions in your query() function yet you are trying to use mysql_fetch_array() to get the results. You need to use: mysqli_fetch_array()
http://www.php.net/manual/en/mysqli-result.fetch-array.php
Actually it looks like your query() function does it for you. You shouldn't need to use a function at all. Look at this section of your query() function:
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
However not sure why it says it is json cause it is just a normal array not a json array. So you should just use this in your code:
$row = $result['result'][0];
This will get the first row.
maybe you have to json_encode the result?
//return json
return json_encode(array('result'=>$rows));
I have the following class. Which returns certain fields. I am interested in Reference. I want it to split up the data so that after the query is returned reference contains an 'A' then return that, if it contains a B return that. seperately so i am able to put it in table show the amount of a's returned, b's returned etc. The data is listed by room.
<?php
class CHWIPProgress {
var $conn;
// Constructor, connect to the database
public function __construct() {
require_once "/var/www/reporting/settings.php";
define("DAY", 86400);
if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error());
if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error());
}
public function ListWIPOnLocation($location) {
$sql = "SELECT DISTINCT
`ProgressPoint`.`PPDescription` AS Description ,`Bundle`.`WorksOrder` AS WorksOrder, `Bundle`.`BundleNumber` AS Reference,`TWOrder`.`DueDate` AS DueDate , `Stock`.`Description` as Stock , `Stock`.`ProductGroup` as Group
FROM TWOrder,Bundle,ProgressPoint, Stock
WHERE `Bundle`.`CurrentProgressPoint`=`ProgressPoint`.`PPNumber`
AND `TWOrder`.`Colour`=`Bundle`.`Colour`
AND `TWOrder`.`Size`=`Bundle`.`Size`
AND `TWOrder`.`WorksOrderNumber`=`Bundle`.`WorksOrder`
AND `TWOrder`.`Product`=`Stock`.`ProductCode`
AND `ProgressPoint`.`PPDescription` = '" . $location . "'
ORDER BY `TWOrder`.`DueDate` ASC";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
$result = mysql_query($sql, $this->conn);
$num_rows = mysql_num_rows($result);
echo "Number of rows : $num_rows";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$return[] = $row;
}
return $return;
}
}
?>
The ListWIPOnLocation function appears to return an array where each item corresponds to a row from the query. You can iterate this array and isolate the items using PHP string functions and perhaps add them other arrays. There is more than one way to arrange the data, here is one example:
$returned = array();
$returned["A"] = array();
$returned["B"] = array();
foreach($return as $row) {
if (strpos($row["Reference"], "A") !== FALSE) { // note the !== operator
$returned["A"][] = $row;
}
if (strpos($row["Reference"], "B") !== FALSE) { // note the !== operator
$returned["B"][] = $row;
}
}
var_dump($returned);
Alternately, You can use the MySQL LIKE operator in the WHERE clause to retrieve the rows where the reference column contains a specific character:
WHERE ... AND Reference = LIKE '%A%'