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');
Related
I'm making a query to my database, but the query always return empty. If I copy the query and paste it directly to mysql, it show one record, as it should be.
This is my query in php:
$sql = "SELECT * FROM disponibilities WHERE st_week = '" .
$st_week . "' AND en_week = '" . $en_week . "' AND boat = '" .
$_POST['boat'] . "'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
$disponibility = $row;
}
} else {
echo "0";
echo $_POST['boat'];
}
And this is the query (echo of the previous query) that show one record if used in phpmyadmin:
SELECT * FROM disponibilities WHERE st_week = '2021-11-13' AND en_week = '2021-11-20' AND boat = 'sapphire'
I've tried converting the date in this way, but still don't work
$sql= "SELECT * FROM disponibilities WHERE st_week =
STR_TO_DATE('$st_week','%Y-%m-%d') AND en_week = STR_TO_DATE('$en_week','%Y-%m-%d')";
EDIT:
this is my phpmyadmin query response:
Thanks in advance
try to run
SELECT * FROM disponibilities WHERE st_week = '2021-11-13' AND en_week = '2021-11-20' AND boat = 'sapphire';
this query from your code what i mean is that run the query with static values instead of variables and see if it returns anything if it does then you are getting wrong value in your variables...
let me if this is the problem if not also so that i can help you further...
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 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.
I am having an issue where I can not search for the exact data I want.
I can search the database fine and return all the values in the format I want. However i want to add in the ability to search by a company's name and also display those results in the same table. The companys Names are not stored in the databse but are in the Array session pulled from an API. We store the ID for each company in the database which is set as the Keys from the array.
I want to know if there is any way to get results given form the array as well as the database search.
I know i can do it with a foreach loop around all my SQL SELECT Statement, but the issue with that is if there is no match in the array it will not run any search, making the rest of the search very limited as searching by IP Address is one of the main reasons for this. the only way I think it is possible is adding a foreach loop into the SQL statement but I don't see how that is possible nor can i find any documentation on it online. please help!
Here is my code that runs based on an input from a search box sent by AJAX.
// Start sessions, Connected to DB set customer array
session_start();
$conn = connect();
$customers = $_SESSION['array'];
// if ajax posted search input
if($_POST){
$search = mysqli_real_escape_string($conn, $_POST['search']);
//set a second input for checking against customers array and format to give results
$input = $search
$input = strtolower($input);
$input = "'$input'";
$result = preg_grep($input, $customers);
$arrayk = array_keys($result);
//SELECT Search mysql Query
$matchingcompanies = "";
foreach($arrayk as $id)
{
$matchingcompanies .= "'" . $id . "' OR ";
}
$matchingcompanies = substr($matchingcompanies,0,strlen($matchingcompanies)-4);
$query1 = "SELECT * FROM IPV4_linked WHERE `companyId` = (" . $matchingcompanies . ") OR concat(ipv4Address, ipv4Subnet, hostName, owner, siteName) like '%" . $search . "%'";
$view4 = mysqli_query($conn, $query1);
//Table Title row
echo "<div><table name ='ipv4' class='tableparent'><td class='tabled'>IP Address</td><td class='table'>Subnet</td><td class='table'>PC Name</td><td class='table'>Owner</td><td class='table'>Customer</td><td class='table'>Customer Site</td></tr>";
//loops through search results and echo table
while ($row = mysqli_fetch_array($view4)){
$id = $row['companyId'];
$company = $customers[$id];
echo "<tr><td class='tabled'>". $row['ipv4Address']."</td><td class='table'>". $row['ipv4Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>".$company."</td><td class='table'>".$row['siteName']."</td></tr>";
}
echo"</table></div>";
}
?>
Solved the issue by adding in a matchingcompanies field before and setting it to an exceeding long string with lots of OR's, i will limit the search to only start after 3 characters inputed so the string return is not so large.
//SELECT Search mysql Query
$matchingcompanies = "";
foreach($arrayk as $id)
{
$matchingcompanies .= "'" . $id . "' OR ";
}
$matchingcompanies = substr($matchingcompanies,0,strlen($matchingcompanies)-4);
$query1 = "SELECT * FROM IPV4_linked WHERE `companyId` = (" . $matchingcompanies . ") OR concat(ipv4Address, ipv4Subnet, hostName, owner, siteName) like '%" . $search . "%'";
$view4 = mysqli_query($conn, $query1);
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)