PHP to sqlite3 - can't upload - php

I have been trying to make a project where I need to upload information to a sqlite3 database. For that I'm using simple PHP scripts.
I succeeded already uploading information from a PHP script to a database with something like this:
<?php
try
{
$db = new PDO('sqlite:mydatabase.db');
$db->exec("INSERT INTO temps (zone,temperature) VALUES ('maia',77)");
echo "Row Inserted\n";
}
catch(PDOException $e)
{
print $e->getMessage();
}
?>
Now I am struggling to do the same with a script lie this:
<?php
$data = htmlspecialchars($_GET["temp1"]);
$file = "temps.txt";
$current = file_get_contents($file);
$current .= $data;
file_put_contents($file, $current);
try
{
$db = new PDO('sqlite:teste1.db');
$db->exec('BEING;');
$db->exec('INSERT INTO temps (temperature) VALUES ($temp1)');
$db->exec('COMMIT;');
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
My table "temps" has a schema like this:
CREATE TABLE temps (temperature NUMERIC);
Is it because of the var type in the PHP since I declared it as numeric in the database? If so how can I solve that?
Appreciate all your ideas.
Thank you

You might be interested in prepapred statements and (named|positional) parameters:
<?php
$temp1 = '1234';
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE temps (temperature NUMERIC)');
$stmt = $db->prepare('INSERT INTO temps (temperature) VALUES (?)');
$stmt->execute( array($temp1) );
}
catch (PDOException $e) {
echo $e->getMessage();
}

Related

PHP 7.x SQLITE3 PDO - is the execute() closing the PDO connection?

I have this code that works weird with SQLITE3 , since the same code with MYSQL works fine
The issue is the line commented with "ISSUE" at line #31, because with MYSQL/MariaDB that "re connection" is NOT needed
Now I better explain
If the IF routine is not entered, I have NO error
If the IF routine is processed, line #34 throws
Uncaught Error: Call to undefined method PDOStatement::prepare()
like if the $PDO-execute(); inside the IF is destroying the PDO istance
You may say, well, no problem, now you have fixed it ... yes, but I'd like to understand why this happen.
Also portability is a point. If this is PDO ... except for the connection, the rest of the script should work and moved among various supported PDO DBs
Thank you if you kindly hint what is the reason and what is it
<?php
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$PDO = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$PDO->bindValue(':testo', $_POST['NoteUpdateText']);
$PDO->bindValue(':id', 1);
$PDO->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
$PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$PDO = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$PDO->execute();
$row = $PDO->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
FIXED CODE
<?php
//include 'db-con2.php';
// table: ajax
// col: testo
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$statement = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$statement->bindValue(':testo', $_POST['NoteUpdateText']);
$statement->bindValue(':id', 1);
$statement->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br> - IF -" . $e->getMessage();
}
}
// carica da DB in ogni caso per caricare il P col testo realmente in DB
//$PDO = new PDO('sqlite:myDatabase.sqlite3');
try {
$statement = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$statement->execute();
$row = $statement->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br> - NORMALE - " . $e->getMessage();
}
?>
Why would you override $PDO variable ?
$pdo = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$stmt = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
if ($stmt->execute(array(':testo'=>$_POST['NoteUpdateText'], ':id' => 1)))
{
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
} else {
// There's error processing updates
// debug
print_r($stmt->errorInfo());
}
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
// There's no need to redeclare $PDO
// $PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$stmt = $pdo->prepare("SELECT testo FROM ajax WHERE id=1 LIMIT 1"); // line #34
$stmt->execute();
$row = $stmt->fetch();
//var_dump($row);
echo $row["testo"];
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

insert postgis geometry with GET values

I'm trying to make an insert using ST_Makepoint with get values, but I run into 500 Error.
This is my php code:
<?php
try {
$user = 'user';
$dbh = new PDO('pgsql:host=localhost;dbname=userdb', $user);
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,?);");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], ST_SetSRID(ST_MakePoint($_GET['lat'], $_GET['long']),4326)))) {
print_r("OK");
} else {
print_r("Error");
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
If I run this query with pgAdmin, it runs well:
INSERT INTO table(id_a, id_b, geom) VALUES (1,1,ST_SetSRID(ST_MakePoint(2, 2),4326));
Do you know how to fix the problem in php code?
I solved in this way:
$stmt = $dbh->prepare("INSERT INTO table(id_a, id_b, geom) VALUES (?,?,ST_SetSRID(ST_MakePoint(?, ?),4326));");
if ($stmt->execute(array($_GET['id_a'], $_GET['id_b'], $_GET['lat'], $_GET['long']))) {
print_r("OK");
} else {
print_r("Errore");
}

PHP :: Stumped on how to reference specific row in a mysql select array...?

I am just not making a connection here, and im not getting search results that are helping me enlighten myself.
I am pulling data from mysql into an array. But I am tottaly missing how I reference a specific row later.
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
foreach($chamberstate as $row) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
$array = array($chamber,$schedule,$runningnow,$temp);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Ok, so all the data is in the array. But how do I , say, print the $schedule where $chamber == 1 ?
I feel so dumb for not getting this.....
You were close with your original code but the $array variable was being overwritten each time through the loop. If you need to access the values throughout your page ou should be able to do so with an approach like this.
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
/* Populate this array for later use */
$chambers=array();
foreach( $chamberstate as $row ) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
/* This will overwrite any values in the $array variable with each iteration through the loop */
/*
$array = array( $chamber, $schedule, $runningnow, $temp );
*/
$chambers[]=array( 'chamber'=>$chamber, 'schedule'=>$schedule, 'running'=>$runningnow, 'temp'=>$temp );
}
/* later, when you need to access the various values, you can reference via the index */
echo $chambers[ 1 ]['chamber'];
/* or */
echo $chambers[ 23 ]['schedule'];
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
$caray = array();
foreach($chamberstate as $row) {
$caray[$row['Chamber']]['Chamber'] = $row['Chamber'];
$caray[$row['Chamber']]['Schedule'] = $row['Schedule'];
$caray[$row['Chamber']]['RunningNow'] = $row['RunningNow'];
$caray[$row['Chamber']]['ChangingTemp'] = $row['ChangingTemp'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
print_r($carray['1']);
?>

PDO Read From Database

I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>

How to catch exact sql error in php pdo statement

I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);

Categories