I have the following Postgres query:
$sql_afect = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
I'm working on a PHP program, and this query sums a bunch of some specific hours, which are in this format on a table (ctl_reportes): '00:00:00'.
How could I save this query's result into a PHP variable in order to echo the result on the screen?
See the code below to execute query in PHP using PDO
<?php
$user = 'root';
$pass = 'toor';
$dbh = new PDO('mysql:host=localhost;dbname=db_scrapper', $user, $pass);
$query = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
$sth = $dbh->prepare($query);
$sth->execute();
/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
var_dump($result);
Here after query is executed, the result is stored in $result. I assume you have some
basic knowledge to use PHP. Please refer to PHP PDO to have more insights into it.
Please let us know if this works for you or not. And I'll update my answer accordingly.
Related
I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.
I'm beginner at PHP & MYSQL I don't know where is the error at this code first MySQL database contains 6 tables I've no equation to JOIN them together and I want to show the last added value of each table
<?php
$servername = "localhost";
$username = "project";
$password = "pro2018";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_temp = "select * from temp order by id desc limit 1 ";
$sql_hum = "select * from hum order by id desc limit 1 ";
$sql_soil1 = "select * from soil1 order by id desc limit 1 ";
$sql_soil2 = "select * from soil2 order by id desc limit 1 ";
$sql_soil3 = "select * from soil3 order by id desc limit 1 ";
$sql_soil4 = "select * from soil4 order by id desc limit 1 ";
$result_temp = $conn->query($sql_temp);
$result_hum = $conn->query($sql_hum);
$result_soil1 = $conn->query($sql_soil1);
$result_soil2 = $conn->query($sql_soil2);
$result_soil3 = $conn->query($sql_soil3);
$result_soil4 = $conn->query($sql_soil4);
//if ($result_->num_rows > 0) {
// output data of each row
$row_temp = $result_temp->fetch_assoc()) ;
$row_hum = $result_hum->fetch_assoc()) ;
$row_soil1 = $result_soil1->fetch_assoc()) ;
$row_soil2 = $result_soil1->fetch_assoc()) ;
$row_soil3 = $result_soil1->fetch_assoc()) ;
$row_soil4 = $result_soil1->fetch_assoc()) ;
$x = $row_temp["value"];
$y = $row_hum["value"];
$a = $row_soil1["value"];
$b = $row_soil2["value"];
$c = $row_soil3["value"];
$d = $row_soil4["value"];
echo " $x" . " Degree";
echo " $y" . " %";
echo " $a" . " %";
echo " $b" . " %";
echo " $c" . " %";
echo " $d" . " %";
header("Refresh:5");
?>
Welcome to Stack overflow!
First off, consider using PDO objects in PHP. PDO are the latest way to talk to databases in PHP. It is a more generalized platform that can talk to many more diffrent types of database. PHP manual here. Outline of differences between MySqli and PDO here(external).
Second, without joining, you can't return the data from more than one table at a time in one SQL SELECT statement. You will need to do multiple requests, as you have in your code example.
You could make the process more streamlined, though, by having an array of the tables you want to get data from:
$tableArray = array(
'tableOne'=>"<name of table one>",
'tableTwo'=>"<name of table two>",
...
);
$resultArray = array();
//get results from server
foreach($tableArray as $curKey=>$curTable){
//ONLY SAFE IF $tableArray IS NEVER CHANGED
$curStmt = "SELECT * FROM ".$curTable." order by id desc limit 1;";
$resultArray[$curKey] = //set this to the result from the sql statement
}
//print them out
foreach($resultArray as $curKey=>$curValue){
echo $curKey. " " . $curValue;
}
This method lets you setup the tables you want to get the info from in one place and do everything you need for you.
Make sure that your list of table names can never be edited though (just never assign it beyond the initial definition). Unfortunately, you cannot use a table name as a parameter for prepared statements, so you must build the sql statements yourself (as shown in my example), opening up the possibility for SQL injection. If you never assign the values of your table array outside of the initial definition, you should be fine though.
( I know the link explaining that tables as parameters doesn't work is specifically for java, but the issue there is SQL querying, not Java based)
I build my query like this:
foreach($ids as $key => $idi) {
$ids[$key] = "'" . $idi . "'";
};
$ids_imploded = implode(", ", $ids);
$sql = "SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN (" . $ids_imploded . ") AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT " . count($ids) . ";";
$result = mysqli_query($con, $sql);
Where $ids is just array of few numbers (so the $ids_imploded = "'132', '165'").
When I run the generated query in phpMyAdmin, I get what I want. When I run it from PHP, it returns just object with nulls. Why?
I doesn't work neither if I remove the escaping loop.
EDIT: generated query is echoed like
SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN ('1614', '1615') AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT 2;
The problem could be that you are querying the wrong database, try select a db first, try executing this before the query :
mysql_select_db('yourdb');
Is the result of your query true ? Check your connection object, it seems like you are not on the right database.
It appears that the query was indeed working even in PHP, but later when I was processing the results, intellisense tricked me and I was using mysql_fetch_assoc instead of mysqli_fetch_assoc...
I'm running the following query using MySQL workbench and I'm getting the exact results from the database :
SELECT *
FROM ODB_RG
WHERE fullAddressV1 = 'רמת גן חרושת 1'
OR fullAddressV2 = 'רמת גן חרושת 1'
OR fullAddressV3 = 'רמת גן חרושת 1'
OR fullAddressV4 = 'רמת גן חרושת 1'
On the other hand, running the following php code does, that actually generated an equivalent query to the one mentioned above,does not return any record :
$fullAddress = "1 רמת גן חרושת";
$stmt = $con->prepare("SELECT * FROM ODB_RG WHERE fullAddressV1 = :address1 "
. "OR fullAddressV2 = :address2 OR fullAddressV3 = :address3 "
. "OR fullAddressV4 = :address4");
$stmt->bindParam(':address1',$fullAddress);
$stmt->bindParam(':address2',$fullAddress);
$stmt->bindParam(':address3',$fullAddress);
$stmt->bindParam(':address4',$fullAddress);
$status = $stmt->execute();
The only reasonable cause that might lead to the difference between the solution is the Hebrew string that is passed as a parameter.
Any of you have any idea what should be done in order to fix it ?
Thanks in advance !
EDIT :
This is the collation i'm using for the relevant table:
engine=MyISAM charset=UTF8 COLLATE = utf8_general_ci;
This is what I meant by error checking:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fullAddress = "1 רמת גן חרושת";
$stmt = $con->prepare("SELECT * FROM ODB_RG WHERE fullAddressV1 = :address1 "
. "OR fullAddressV2 = :address2 OR fullAddressV3 = :address3 "
. "OR fullAddressV4 = :address4");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($con->errorInfo());
die();
}
$stmt->bindParam(':address1',$fullAddress);
$stmt->bindParam(':address2',$fullAddress);
$stmt->bindParam(':address3',$fullAddress);
$stmt->bindParam(':address4',$fullAddress);
$status = $stmt->execute();
if (!$status ) {
echo "\nPDO::errorInfo():\n";
print_r($con->errorInfo());
die();
}
if($row = $stmt->fetch()){
var_dump($row);
}else{
echo 'no row found';
}
I know its ulgy, sometime called defensive programming, but it lets you know whats going on.
I'm trying to populate a previously created table from an insert select job in PHP.
Google documentation has a short paragraph that say the next:
"Run an asynchronous query, pass in the name of your existing table, and set writeDisposition=WRITE_APPEND."
Now I'm getting rows from bigquery using next sentences :
// query request service
$query = new Google_Service_Bigquery_QueryRequest();
//armar query
$selectQuery = "select source_year, year, month, day from publicdata:samples.natality LIMIT 100";
if($whereQuery!=null && strlen($whereQuery)>0)$selectQuery = $selectQuery . " WHERE " . $whereQuery;
//print_r(var_dump($selectQuery));
$query->setQuery($selectQuery);
$response = $service->jobs->query($project_id, $query);
$jsonStr = "";
if($response)if($response->getRows())$jsonStr = $response->getRows();
print_r($jsonStr);
But I need to populate another table from the query result.
Thank you for your advices.
Bye
Thank you Pentium10 but I'm receiving the error message "Call to undefined method Google_Service_Bigquery_QueryRequest::setDestinationTable() " because I'm not using a job to execute the query.
I working with the next sentences to get the query result but Its didn't work:
//query request service
$query = new Google_Service_Bigquery_QueryRequest();
//destination table
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId($dataset);
$destinationTable->setProjectId($project_id);
$destinationTable->setTableId('ventastest');
$query->setDestinationTable($destinationTable);
$query->setWriteDisposition('WRITE_APPEND');
//build query
$selectQuery = "SELECT " . $fieldsQuery . " FROM " . $dataset . "." . $tableQuery;
if($whereQuery!=null && strlen($whereQuery)>0)$selectQuery = $selectQuery . " WHERE " . $whereQuery;
$query->setQuery($selectQuery);
$response = $service->jobs->query($project_id, $query);
$jsonStr = "";
if($response)if($response->getRows())$jsonStr = $response->getRows();
print_r($jsonStr);
Even if I attach to the service->job I receive the error message:
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId($dataset);
$destinationTable->setProjectId($project_id);
$destinationTable->setTableId('ventastest');
$service->jobs->setDestinationTable($destinationTable);
$service->jobs->setWriteDisposition('WRITE_APPEND');
Thanks and bye!
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('name_of_the_table');
$queryConfig->setDestinationTable($destinationTable);
$queryConfig->setWriteDisposition('WRITE_APPEND');