I have a select statement see below. Using PDO how would I recreate this same Select statement, as I want to grab two values from it and combine them into the $geomstring. I can figure out the combine, but not the first 3 lines.
$sql1 = "SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id='$_POST[gridref_id]'";
$result1 = pg_query($sql1);
$row1 = pg_fetch_array($result1);
$geomstring = $row1['easting_value']. $_POST['grid_eastings']." ".$row1['northing_value'].$_POST['grid_northings'];
*php website for prepared statements says *
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
I have something similar working for populating a dropdown that partly uses this
$stmt = $conn->prepare("SELECT easting_value, northing_value FROM gridreference_tbl WHERE gridref_id=$gridref_id");
$stmt->setFetchMode(PDO::FETCH_OBJ);
Found it on php.net, I was googling the wrong stuff:
$stmt4 = $conn->prepare("SELECT easting_value, northing_value from gridreference_tbl WHERE gridref_id = 4");
$stmt4->execute();
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $stmt4->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");
Related
When I use full PDO query:
$db = DB::singleton();
$stmt = $db->prepare("SELECT * FROM promocode WHERE status = 1 AND code='xyz'");
$stmt->execute();
PhpStorm recognize table scheme and it suggests syntax & show wrong column name - Nice!
...but, most often I use db like this:
public function get($coupon)
{
/* table:promocode */
$db = $this->db()->retObj();
$db->where('status = 1 AND code = ?', [$coupon]);
return $db->fetch();
}
Is there any "magic" comment like (table:promocode) to tell PhpStorm that it is DB syntax?
I'm trying to a segment of code which is behaving strange.
I am using the Paul Irish infinite scroll with the JQuery masonry plugin to display content.
The content is pulled by sql and has a set number, currently 20.
This means the page will load the first 20 rows of content from the database, then will load the next 20 upon scrolling down.
I have this functionality on a few pages and it works fine except for one page.
On this page instead of loading the most recent 20 posts, it loads every post in that particular field. Some have over 5000 posts so it literally crashes the page. A major problem as you can imagine.
I have been trying to adapt the code to look for anomalies and have narrowed it down (I think) to one particular segment.
This is the code used on a page that works:
function index() {
$userID = false;
$order = false;
$limit = $this->config->item('pin_load_limit');
$page = $this->uri->segment(3, 1);
$nextOffset = ($page -1) * $limit;
$nextPage = $page +1;
$sql = "SELECT *
FROM
pins";
if ($userID)
$sql .= " WHERE
user_id= $userID ";
if ($order) {
$sql .= " ORDER BY
' $order'";
} else {
$sql .= " ORDER BY time DESC";
}
$sql .= " LIMIT $nextOffset,$limit";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->result();
}
This is the code on the page that doesn't work:
function getEachBoardPins($id,$limit=false)
{
$sql = "SELECT
*
FROM
pins
WHERE
board_id = $id
ORDER BY time DESC";
if($limit)
$sql .=" LIMIT 0 ,$limit" ;
$query = $this->db->query($sql);
return $query->result();
}
I know it is to do with the pin load limit but I have tried adding the code to the latter without success.
Perhaps somebody on here who knows more about it can provide some better insight?
I imagine that it is VERY LIKELY that when you call the "getEachBoardPins" function, you aren't setting the second parameter, hence, it is defaulting to false, hence, the limit SQL isn't being appended, so the select statement will run the whole statement.
I have a query that returns c.a 1800 records( not many) but It takes long time to ran (10 seconds) but I can not understand why?
this is my query that takes a long time:
SELECT tb_KonzeptFunktionen.Konzept AS KonzeptID, tb_KonzeptFunktionen.Funktion,
tb_KonzeptFunktionen.Version,
qryFunktionen_Übersicht.ID,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar AS Kommentar,
qryFunktionen_Übersicht.Fehlerpfadname,
qryFunktionen_Übersicht.Fehlerpfad_CDT,
qryFunktionen_Übersicht.Fehlerpfad_Kommentar,
qryFunktionen_Übersicht.symptombasiert,
qryFunktionen_Übersicht.Beschreibung_vorhanden,
qryFunktionen_Übersicht.Max_Pfad,
qryFunktionen_Übersicht.Max_Info,
qryFunktionen_Übersicht.Max_Status,
qryFunktionen_Übersicht.Max_Strategie,
qryFunktionen_Übersicht.Max_Prüfplan,
qryFunktionen_Übersicht.Min_Pfad,
qryFunktionen_Übersicht.Min_Info,
qryFunktionen_Übersicht.Min_Status,
qryFunktionen_Übersicht.Min_Strategie,
qryFunktionen_Übersicht.Min_Prüfplan,
qryFunktionen_Übersicht.Sig_Pfad,
qryFunktionen_Übersicht.Sig_Info,
qryFunktionen_Übersicht.Sig_Status,
qryFunktionen_Übersicht.Sig_Strategie,
qryFunktionen_Übersicht.Sig_Prüfplan,
qryFunktionen_Übersicht.Plaus_Pfad,
qryFunktionen_Übersicht.Plaus_Info,
qryFunktionen_Übersicht.Plaus_Status,
qryFunktionen_Übersicht.Plaus_Strategie,
qryFunktionen_Übersicht.Plaus_Prüfplan,
qryFunktionen_Übersicht.Beschreibung_allgemein,
qryFunktionen_Übersicht.Funktionsname
FROM tb_KonzeptFunktionen RIGHT JOIN qryFunktionen_Übersicht
ON tb_KonzeptFunktionen.Funktion = qryFunktionen_Übersicht.Funktionsname
WHERE (((tb_KonzeptFunktionen.Konzept)=[Formulare]![frm_Fahrzeug]![ID]))
and this is another related query to above query:
SELECT tbFunktionen_Übersicht.*,
tbFunktionen.Funktionsname,
tbFunktionen.Funktionsbeschreibung,
tbFunktionen.diagnoserelevant,
tbFunktionen.ID AS FunktionsID
FROM tbFunktionen_Übersicht INNER JOIN tbFunktionen
ON tbFunktionen_Übersicht.Funktion = tbFunktionen.ID
ORDER BY tbFunktionen.Funktionsname, tbFunktionen_Übersicht.Fehlerpfadname;
I added an index to the fields that appear in ORDER oder JOINS but no effect
Would you please help me if possible?
Please refer to this post,hier you can find the answer
for me PDO brought improvement in my sql query's: http://www.php.net/manual/en/intro.pdo.php
//SQL-HANDLING*******************************************************//
//*********************************************************************//
//General Example-----------------
//$sqlHandling = new sqlHandling;
//$sqlHandling->connectSQL($sqlArray['host'], $sqlArray['user'],$sqlArray['pass'], $sqlArray['dbName']);
//$tableNameArray = $sqlHandling->showTablesSQL($sqlHandling->dbh);
class sqlHandling{
//PDO - Object/ callItOutside with: $sqlClass->dbh
public $dbh = null;
//connectDataBase-------------------//
//-----------------
//example: $dbh = connectSQL('localhost','admin','1admin','test');
//start transaction
//$dbh->beginTransaction();
//-----------------
//end transaction
//$dbh->commit();
//$dbh = null;
//-----------------
//1:SQL-Location
function connectSQL($host, $user, $pass, $dbname){
//endPrevTransaction
if($this->dbh != null){
$this->dbh->commit();
$this->dbh = null;
}
//establish connection
try{
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
$this->dbh->exec('SET CHARACTER SET utf8');
return $this->dbh;
}catch(PDOException $e){
print 'Error!: ' . $e->getMessage() . '<br/>';
die();
return FALSE;
}
}
//createColumnSQL-------------------//
//example: createColumnSQL($dbh, 'backupexample', array('SomeName1 VARCHAR(30)', 'SomeName2 VARCHAR(30)', 'SomeName3 VARCHAR(30)', 'SomeName4 VARCHAR(30)'));
//1:PDO connection/2:table/3:array holding columns
function createColumnSQL($dbh, $table, $columns){
//cicle through each array
foreach($columns as $tempColumn){
//set query
$query = 'ALTER TABLE `'.$table.'` ADD COLUMN '.$tempColumn;
//send the query
$stmt = $dbh->prepare($query);
//send the data
$stmt->execute();
}
}
}
This is only a working example for my PDO sqlHandling Class. I know retrieveAllValues won't help you further but you may adopt this code for your use.
MFG
I want to optimize some of the SQL and just need an opinion on whether I should do it or leave it as is and why I should do it. SQL queries are executed via PHP & Java, I will show an example in PHP which will give an idea of what Im doing.
Main concerns are:
-Maintainability.
-Ease of altering tables without messing with all the legacy code
-Speed of SQL (is it a concern???)
-Readability
Example of what I have right now:
I take a LONG array from a customer (cant make it smaller unfortunately) and update the existing values with the new values provided by a customer in the following way:
$i = 0;
foreach($values as $value)
{
$sql = "UPDATE $someTable SET someItem$i = '$value' WHERE username='$username'";
mysql_query($sql, $con);
$i+=1;
}
Its easy to see from the above example that if the array of values is long, than I execute a lot of SQL statements.
Should I instead do something like:
$i = 0;
$j = count($values);
$sql = "UPDATE $someTable SET ";
foreach($values as $value)
{
if($i < $j) //append values to the sql string up to the last item
{
$sql .= "someItem$i = '$value', ";
}
$i+=1;
}
$sql .= "someItem$i = '$value' WHERE username='$username'"; //add the last item and finish the statement
mysql_query($sql, $con); //execute query once
OR which way should it be done / should I bother making these changes? (there a lot of the type and they all have 100+ items)
Thanks in advance.
The only way you'll get a definitive answer is to run both of these methods and profile it to see how long they take. With that said, I'm confident that running one UPDATE statement with a hundred name value pairs will be faster than running 100 UPDATE statements.
Don't run 100 seperate UPDATE statements!
Use a MySQL wrapper class which, when given an array of name => value pairs will return an SQL UPDATE statement. Its really simple. I'm just looking for the one we use now...
We use something like this (registration required) but adapted a little more to suit our needs. Really basic but very very handy.
For instance, the Update method is just this
/**
* Generate SQL Update Query
* #param string $table Target table name
* #param array $data SQL Data (ColumnName => ColumnValue)
* #param string $cond SQL Condition
* #return string
**/
function update($table,$data,$cond='')
{
$sql = "UPDATE $table SET ";
if (is_string($data)) {
$sql .= $data;
} else {
foreach ($data as $k => $v) {
$sql .= "`" . $k . "`" . " = " . SQL::quote($v) . ",";
}
$sql = SQL::trim($sql , ',');
}
if ($cond != '') $sql .= " WHERE $cond";
$sql .= ";";
return $sql;
}
If you can't change the code, make sure it is enclosed in transaction (if the storage engine is InnoDB) so no non-unique indexes will be updated before commiting transaction (this will speed up the write) and the new row won't be flushed to disk.
If this is MyISAM table, use UPDATE LOW_PRIORTY or lock table before the loop and unlock after read.
Of course, I'm sure you have index on the username column, but just to mention it - you need such index.
$dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
foreach $data_line (#raw_data) {
$SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = '$data_line'";
$sth = $dbh_source2->prepare($SEL);
$sth->execute();
while (my #row = $sth->fetchrow_array() ) {
print #row;
print "\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
I am trying to grab several lines of data from a user. I want to take that data and use it to query a database and grab ARG1 and ARG2 WHERE USER_DATA = $data_line.
It will not display anything.
Here's a quick revision which uses SQL placeholders in order to keep Bobby Tables from destroying your database. It may also fix the problem you're currently having, but I haven't seen enough details of your problem yet to be sure.
my $dbh_source2 = DBI->connect("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);
foreach my $data_line (#raw_data) {
$sth->execute($data_line);
while (my #row = $sth->fetchrow_array() ) {
print #row;
print "\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
my $dbh_source2 = DBI->connect
("dbi:Oracle:host=.......;port=......;sid=......",'..........','..........');
my $SEL = "SELECT arg1,arg2 FROM TABLE_NAME WHERE DATA_NAME = ?";
my $sth = $dbh_source2->prepare($SEL);
foreach my $data_line (#raw_data) {
chomp $data_line;
$sth->execute($data_line);
while (my #row = $sth->fetchrow_array() ) {
print "$data_line\t #row\n";
}
}
END {
$dbh_source2->disconnect if defined($dbh_source2);
}
The issue I was having was the fact that the development database was not updated with the correct information so some of the items came up blank. When using the production database with the correct information it worked great!
Thank you all for your help!