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();
}
Related
Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>
MY code is:
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
$stmt->bindParam(':email', $username);
$stmt->bindParam(':pass', $password);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$_SESSION['uid']=$stmt->fetchColumn(0); //working
$_SESSION['fname']=$stmt->fetchColumn(1); //not working
$utype=$stmt->fetchColumn(3); // not working
if($utype == "admin")
{
// send to admin page
}
else
{
//send to user page
}
}
else
{
echo"Incorrect data.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I am new to PHP, I basically do Java.
I read here that:
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
In java, there is ResultSet#getString() funtion to do this.
What is the PHP equivalent of this?
You can use:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
Please read this
fetchColumn(), Returns a single column from the next row of a result
set.
Please read this for detail.
Use PDO::fetchAll() :
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}
or just print_r($rows) you will notice that it's an associative array.
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;
}
}
?>
I am developing my first project using Amfphp and am writing my first simple Service. Here is my getData method:
public function getData() {
// Connect to the database using PHP Data Objects (PDO).
try {
$pdo = new PDO('mysql:host=localhost;port=8889;dbname=amf_test', 'root', 'root');
} catch (PDOException $e) {
print "Connection Error!: " . $e->getMessage() . "<br/>";
die();
}
// Set an Error Handling mode.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully\n";
// Retrieve all rows.
$tsql = 'SELECT * FROM authors_aut';
$stmt = $pdo->prepare($tsql);
$stmt->execute();
// Echo the SQL Error Code
echo "SQL Error code: " . $pdo->errorCode() . "\n";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row_count = $stmt->rowCount();
echo $row_count.' rows selected' . "\n";
foreach ($pdo->query($tsql) AS $row) {
$id_aut = $row['id_aut'];
$fname_aut = $row['fname_aut'];
printf("Data: %s (%s) <br />", $id_aut, $fname_aut);
}
// Close the database connection
$stmt = null;
$dbh = null;
// Return the array.
return $results;
}
When I go to the Amfphp Back Office Service Browser, select my getData method and call it I get my comments but no data. Before I added my echo and printf lines I didn't the Service Browser returned nothing leaving me thinking my Service was not working (it still may not be!). My comments appear to show that I have successfully selected the data from the MySQL database but is it being returned?
I welcome your thoughts.
Chris
I'm having some trouble inputting some data into a table.
I'm retrieving some values from a form and inputting them to a table, but this error shows up every time:
Error: Unknown column 'planner_id' in 'field list'
<?php
session_start();
include 'conexion_data.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$teacherid = $_POST["teacherid"];
$plannerid = $_POST["plannerid"];
$yeargroup = $_POST["yeargroup"];
$subject = $_POST["subject"];
$planner_event = htmlspecialchars($_POST["event_comment"]);
$event_date = $_POST["event_date"];
echo "$teacherid $plannerid $yeargroup $planner_event $event_date <br/><br />";
if (empty($event_date) or empty($planner_event)) {
echo "One of the fields was left blank! <br />";
} else {
$sql = "INSERT INTO subject_directorio (planner_id, teacher_id, subject, yeargroup, date, comment ) VALUES ('$plannerid', '$teacherid', '$subject', '$yeargroup', '$event_date', '$planner_event')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
/* header('Location: user_area.php'); */
echo "Data was inputed to DB";
mysqli_close($con);
}
}
?>
It's very straight
while you are getting this type error :{Error: Unknown column 'planner_id' in 'field list'}
Troubleshoot first step will be Just Describe The Table [subject_directorio]
Desc subject_directorio and check planner_id is exist or not. According to to the error
subject_directorio not holding any column called as planner_id
Hope it helps!!
It's self explanatory that your table doesn't have a column planner_id. Even if you see that it has, you may have trialing spaces before or after planner_id in the column name. Check carefully.
Database
You are using wrong way how to connect to database and fetch its data.
Because you database may be hacked using SQL Injection
The right way how to do this is:
Using PDO
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
For error catching:
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And data fetching:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using Mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
And your problem
I think problem is in your query and binding params to it.So try to use proper way as I shown you, and then show us results.
SQLFiddle