function php not show result from two queries - mysql

I try write a function. Its put $row->idf value from first select query to second select query and show sum of zaloha for each idf, but if I want to use $row->idf for show name of it show nothig. If I write only queries without function its working. Why? Thanks
<?php
function zalBoss () {
global $conn;
$fir = 'SELECT * FROM firma WHERE faktiv = 1';
$res = $conn->query($fir);
while ($row = $res->fetchObject()) {
$quer = 'SELECT SUM(zaloha) AS zaloha FROM obchody WHERE firma = '.$row->idf.' AND stav = 2';
$result = $conn->query($quer);
$rw = $result->fetchObject();
echo $firma_array[$row->idf].': '.$rw->zaloha.'<br>';
}
}
zalBoss();
?>
EDIT:
$firma_array is included with file include('obr/sel.php');
$firma_array = array();
$tdb = 'SELECT * FROM firma ORDER BY idf';
$vysl3 = $conn->query($tdb);
while ($riadok1 = $vysl3->fetchObject())
{
$firma_array[$riadok1->idf]=$riadok1->fmenoskr;
}

Related

how to get the number of rows in mysql statements and return it?

I am currently having problem getting the number of rows in my code. here's my code:
$app->get('/banana/:state', function($state) use ($app){
$db = new DbOperation();
$today = date("j-M-Y");
if($state == "Indoor"){
$result = $db->getAllbananaindoor($today);
$response = array();
$response['messages'] = array();
$row = $result->fetch_assoc();
if($row > 3){
$temp = array();
$temp['text'] = 'Yes, you can plant banana seeds today indoors.';
array_push($response['messages'],$temp);
}
else {
$temp = array();
$temp['text'] = 'Nope. Today is not a good time to plant banana seeds indoors.';
array_push($response['messages'],$temp);
}
echoResponse(200,$response);
}
}
public function getAllbananaindoor($today){
$stmt = $this->con->prepare("SELECT * FROM garden WHERE humid >? AND time=? AND temp BETWEEN ? AND ?");
$hum = '50';
$one = '19';
$two = '24';
$stmt->bind_param("iiii",$hum, $today, $one, $two);
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
In this I get the database data from a function getAllBananaindoor() which returns the result instead i want it return the number of rows and finally check whether $row is greater than 3 and then work on that. how can I do that? please help.
The MySQLi Result object has num_rows property defined.
$students = $stmt->get_result();
return $students->num_rows; // will return the number of rows

Get row counts from a multiple

I'm executing a multi-delete DELETE query, like so:
$query = "DELETE FROM foo WHERE 1 = 1; DELETE FROM bar WHERE 1 = 1";
$statement = $this->getEntityManager()->getConnection()->prepare($query);
$statement->execute();
I'm aware that I can use $statement->getRowCount() if my query contained a single delete, but how can I both row counts?
AFAIK there is no way doing this in doctrine, but another solution could be:
$queries = [
"DELETE FROM foo WHERE 1 = 1;",
"DELETE FROM bar WHERE 1 = 1;"
];
$connection = $this->getEntityManager()->getConnection();
$affectedRows = 0;
foreach($queries as $query)
{
$statement = $connection->prepare($query);
$statement->execute();
$affectedRows = $affectedRows + $statement->getRowCount();
}

SQL QUERY SELECT INSIDE A FUNCTION

I am trying to work with a voting database system. I have a form to display all the candidates per candidate type. I'm still trying to to explore that. But this time, I want to try one candidate type, lets say for Chairperson, I want to display all candidate names for that type in the ballot form. However, there's an error with the line where i declare $query and made query statements, can somebody know what it is. I am very certain that my syntax is correct.
function returnAllFromTable($table) {
include 'connect.php';
$data = array ();
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1'; //ERROR
$mysql_query = mysql_query ( $query, $conn );
if (! $mysql_query) {
die ( 'Go Back<br>Unable to retrieve data from table ' . $table );
} else {
while ( $row = mysql_fetch_array ( $mysql_query ) ) {
$data [] = $row;
}
}
return $data;
}
As #Darwin von Corax says, I sure that you have a problem between $table and WHERE
Your query:
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1';
If $table = 'Chairperson';
You have:
'SELECT * FROM ChairpersonWHERE candidateId=1';
The your query should be:
$query = 'SELECT * FROM ' . $table. ' WHERE candidateId=1';

Mysql / PDO - Setting Variable

I'm having trouble trying to set a variable then use it in a select statement. I keep getting a "general error" and can't figure out what I'm doing wrong. Any input would be appreciate. I'm trying to set a variable using subqueries with named parameters.
$query = $dbh->prepare("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = :customer) - (SELECT SUM(charges) FROM charges WHERE customer = :customer); SELECT #available");
$query->bindParam(":customer", $customer);
$query->execute();
If you want to use MySQL user variables, for some reason, you don't need multi-queries support. They (user variables) live as long as you session (connection) is open. Therefore you can do something like this
$customer = 1;
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SET #available = (SELECT SUM(payments) FROM payments WHERE customer = ?) -
(SELECT SUM(charges) FROM charges WHERE customer = ?)";
$query = $db->prepare($sql);
$query->execute(array($customer, $customer));
$query = $db->prepare("SELECT #available");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Exeption: " .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
Sample output:
array(1) {
[0]=>
array(1) {
["#available"]=>
string(6) "100.00"
}
}
PDO doesn't seem to offer any formalised support for multi-queries (but some support does seem to be available), but mysqli does. Neither offer support for prepared multiple statements, though.
You can use mysqli like this:
$mysqli = new mysqli('servername', 'username', 'password', 'dbname');
$query = sprintf("Set #available = (SELECT SUM(payments) FROM payments WHERE customer = %1$s)" .
" - (SELECT SUM(charges) FROM charges WHERE customer = %1$s);".
" SELECT #available",
$mysqli->real_escape_string($customer) );
// Following code lifted from PHP Manual.
// This code will read multiple results, if they're available.
// Your query only returns one.
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
The reference is here

Mysql query shows date results a little mixed up

I'm trying to get a minimum and maximum temperature from a database for each day.
But he retrieves the date year in wrong order I get values like this:
Array ( [00-00-0000] => 22 [00-08-2013] => 22 [01-08-0201] => 24 [01-08-0213] => 24 [01-08-2013] ...
if I verify the data from the table with PHPmyAdmin everithing seems ok.
code:
$query = "SELECT DATE_FORMAT(`Datum`, '%d-%m-%Y') as Datum1, min(`Temperatuur`)as minTemp ,max(`Temperatuur`)as maxTemp FROM `tableGreenhouse` GROUP BY `Datum1` ORDER BY 1";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date = $row['Datum1'];
$Temp1 = $row['minTemp'];
$Temp2 = $row['maxTemp'];
$dataArray1[$date]=$Temp1;
$dataArray2[$date]=$Temp2;
}
}
print_r($dataArray1);
print_r($dataArray2);
There doesn't appear to be anything wrong with your query.
Maybe you could try casting the variables to a certain type using the following code:
if ($result->num_rows > 0) {
// In some cases, code breaks if you do not do this...
// Experienced it myself a few times.
$dataArray1 = array();
$dataArray2 = array();
while($row = $result->fetch_assoc()) {
/* For error checking, enable following statement: */
// var_dump($row);
$date = (string)$row['Datum1'];
$Temp1 = (float)$row['minTemp'];
$Temp2 = (float)$row['maxTemp'];
$dataArray1[$date]=$Temp1;
$dataArray2[$date]=$Temp2;
}
}