How to print the contents of a query to a blank page - php

Hello everyone,
Just a quick question, I am querying a database and i was wondering can anyone help me print the results of the query from a database into a new tab window. I think i have an idea on how to do it, but can someone guide me. So before i call the $statement->execute(); function in php should i create a tag?
So for example,
<?php
if (isset($_GET['submit'])) {
$stat = (!empty($_GET['stat']) ? trim($_GET['stat']) : '');
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $databasehost, $dbname);
$database_handler = new PDO($dsn, $dbuser, $dbpass, array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
$statement = $database_handler->prepare("SELECT * FROM tags WHERE bin = "Teller";)
$statement->bindParam(':stat', $stat, PDO::PARAM_STR);
$statement->execute();
$queryResult = $statement->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['queryResult'] = $queryResult;;
$statement->execute();
}
catch (PDOException $e) {
print "Error: " . $e->getMessage();
}
?>
Is this possible? Please mind my lack of knowledge, i am a beginner in php.

Related

The best and most secure way to echo results with pdo

Hi i am new to PDO and i just learn how to make a Query, i have read a lot about this everywhere on the internet, without luck, and then i tryed this, but i am still wondering if this is the right way to do it? How is the best way to make this to a class, because when i tryed, i did not got any kind of error, and any respond either.
<?php
require_once 'dbconfig.php';
// (echo test) $name_structure='%s';
// (echo test) $title_structure='%s';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT *
FROM portfolio';
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf($name_structure, $r['name']);
echo sprintf($title_structure, $r['title']);
echo sprintf($description_structure, $r['description']);
echo sprintf($img_structure, $r['img']);
echo sprintf($project_end_structure, $r['project_end']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
As you forgot to explain what is "this" you are trying, here are two possible scenarios:
In case "this" is for getting all the records from database, the code would be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->query('SELECT * FROM portfolio');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
in case "this" is about selecting only certain records, code it as follows
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare('SELECT * FROM portfolio WHERE name LIKE ?');
$stmt->execute(array('%son'));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
echo $row['title'];
echo $row['description'];
echo $row['img'];
echo $row['project_end'];
}
How is the best way to make this to a class,
PDO is already a class, mind you. So, insead of making it into another, just learn how to use PDO.
i have read a lot about this everywhere on the internet, without luck,
Here you go, I wrote a tutorial that makes sense (at least for anyone who have basic PHP/SQL training), The only proper guide on PDO

My openshift application PDO query didn't work

I am try to connect phpmyadmin database using my php script in openshift
but the result is a empty page.
then, I find the question is the query didn't work
but I don't know why
There is my original code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('SELECT * FROM test1');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
and the result is a empty page, so I modify my code
There is my modify code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
I input the wrong query sytanx(jngfcjfgcnmgcm,,hmnxf), but it didn't return error.
Add this to your script see your errors
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);
ini_set('html_errors', 1);
and change your query code to this, see notes
try{
//port=***** is only need where its different from the default
$dsn = 'mysql:host=localhost;dbname=exampleDataBase';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dbh = new PDO($dsn, "account", "password", $options);
$sth = $dbh->prepare('SELECT * FROM test1');
// execute $sth
$sth->execute();
//Change fetch to fetchAll
while($row = $sth->fetchAll(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e->getMessage();
}
You modified your code to a wrong statement to see the error message?
You have your PHP errors turned off, when doing a statement like:
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
You would receive an error like:
Sytan errorSQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'jngfcjfgcnmgcm,,hmnxf' at line 1
What do you exactly want? The exception is not showing?

Windows Azure MaxSizeInByte Statement

i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>

PDO Bind Param Trouble

I'm trying to convert my codes to PDO from mysql_query, and starting with this function
function label_for_field($field_name, $table_name) {
$table = array();
// Bind variables to parameters
$param_array = array(':bundle' => $table_name, ':field_name' => $field_name);
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
// Execute
$STH -> execute($param_array);
// Set the fetch mode
$STH -> setFetchMode(PDO::FETCH_OBJ);
while ($row = $STH -> fetch()) {
$info = unserialize($row -> data);
$table[] = $info['label'];
}
return $table[0];
}
and I'm trying out just output it to see if it works
include_once ("includes/connect.php");
include ("includes/functions.php");
echo label_for_field("field_account_number", "account_table");
And here's the connect.php
// Include Constants
require_once ("constants.php");
//Establish Connection
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch (PDOException $e) {
echo $e -> getMessage();
}
I don't know if it's because I'm binding the parameters wrong, it just gave me an server error page
"Server error. The website encountered an error while retrieving ......."
Thanks in advance
You need to set the PDO error mode to produce exceptions before you can catch them.
In your connect.php:
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Then you can have a similar try/catch statement in your function to that of your connection file, and use it to show the error in your development environment.
Try this instead to see if you get valid objects returned from the query.
// Prepare Query Statement
$query = "SELECT data FROM field_config_instance WHERE bundle = :bundle AND field_name = :field_name";
$STH = $DBH -> prepare($query);
$STH->bindValue(":bundle", $table_name);
$STH->bindValue(":field_name", $field_name);
$STH->execute();
$STH->setFetchMode (PDO::FETCH_OBJ);
$result = $STH->fetchAll();
var_dump($result);

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories