Amfphp Service Browser Not Displaying MySQL Result - php

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

Related

Update query is not reflected into database phpmyadmin

Update query is not reflected into database . This is related to PHP and PDO method of connection. The query I have written is ,
try {
$conn = new PDO('mysql:host=localhost;dbname=***; charset=utf8','root','****[enter image description here][1]');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM providers WHERE password = '$oldpass'";
$statement = $conn->prepare($sql);
$statement->execute();
$providers = $statement->fetchAll();
if(($providers[0]["password"]=="$oldpass") and ("$pass"=="$cpass")){
$statement = $conn->prepare('update providers set password="$cpass" where password="$oldpass"');
$condition=$statement->execute();
echo '<script>alert("Password changed")</script>';
}
else{
echo '<script>alert("Incorrect old password");</script>';
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
EDIT The message on entering corresponding credentials is Password changed.
Is there anything wrong with the query??
Because it does not show the updated password in database (phpMyAdmin)
The changes you've made will only be visible inside the same transactions, and would be implicitly rolled back when you close the connection. In order to persist them in the database, you need to commit them:
$conn->commit();

Pulling Queries from Database Clears Results on Error vs. Stopping

We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don't want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?
Connection to Database:
<?php
$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';
try {
$db = new PDO($constr, $dbUser, $dbPW);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$rez = "Connected";
//echo $rez;
} catch(PDOException $ex) {
$rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
//echo $rez;
}
?>
Code to display the results on the page:
<?php
include 'db.connect.php';
$sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";
$stmt = $db->prepare($sql);
$stmt->execute();
$num_rows = $stmt->rowCount();
//echo $num_rows;
if($num_rows > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['ts_id'];
$name = $row['name'];
echo "<tr>";
echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
echo "</tr>";
}
include 'db.close.php';
?>
Thank you in advance!
You might try changing your query to:
$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";
I don't know if that will filter out your error message

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();
}

What is the best way to validate if a record was inserted successfully?

What is the best way to validate if a record was inserted successfully?
I'm using PDO Statements.
This:
/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
include ("./businesslogic/dbconnection/cfg.php");
try {
$db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
$sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
$sql->bindParam(':filename',$filename);
$sql->bindParam(':userid',$userid);
$sql->execute();
$sqlresult = $sql->rowCount();
$db = null;
return $sqlresult; //Then validate if result is greater than 0.
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
}
or this:
/*******************
Update user picture
********************/
function updateuserpicture($userid, $filename) {
include ("./businesslogic/dbconnection/cfg.php");
try {
$db = new PDO('mysql:host='.$server.';dbname='.$db,$db_user,$db_password);
$sql = $db->prepare("Update usersdata set userpicture=:filename where userid=:userid");
$sql->bindParam(':filename',$filename);
$sql->bindParam(':userid',$userid);
if ($sql->execute()) {
$db = null;
return TRUE;
} else {
$db = null;
return FALSE;
} //Then validate if result is TRUE or FALSE.
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
}
Both ways works fine but im not sure what is the best, can you please help me?
PDO won't actually throw exceptions unless you tell it to. So your try..catch is entirely superfluous and will never do anything.
If the statement was executed without error, that means the data was inserted/updated successfully. No need to count rows, unless you are interested in the specific details of how many rows were altered (which is a different topic than "is the data in my database now?").
Given this, I'd recommend to set PDO to throw exceptions in case of errors and not do any further explicit checking:
$db = new PDO("mysql:host=$server;dbname=$db", $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db->prepare('UPDATE users SET userpicture = :filename WHERE userid = :userid');
$sql->bindParam(':filename', $filename);
$sql->bindParam(':userid', $userid);
$sql->execute();
This may still mean that the statement did nothing if the user id didn't exist. This would point to a deeper bug in your app, it's questionable if the PDO code should care about it specifically.

Sqlite PDO query returns no results

Getting no results no matter how broad my query
PHP: 5.3
Sqlite3: 3.6
PDO: 5.3.3
I would think this should be a very simple process but even looking around I still don't know why I'm getting 0 results. Here is my code:
<?php
$sqlite = new PDO('sqlite:/example.db');
$result = $sqlite->query('SELECT * from foo');
if(!$result)
{
echo 'fail';
return false;
}
?>
Any ideas on what I am doing wrong? The 'foo' table will only have four columns, and this test db only has one table. Running the query in sqlite displays the results fine.
You have to execute the statement first than fetch the result.
You might add try/catch block around the execute method call. and do some error handling.
Here's an example of catching an Exception. Do not use it as a design guideline.
<?php
try
{
$sqlite = new PDO('sqlite:/example.db');
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$statement = $sqlite->prepare('SELECT * from foo');
try
{
$statement->execute();
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
$result = $statement->fetchAll();
var_dump($result);
?>

Categories