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);
Related
I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);
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?
I am trying to query out a result, it works in SQL query, but I'm trying to get the result using PHP
SELECT prs_amtdb FROM `prs` WHERE prs_amtcrck = 0
Using mysqli
Note: Make sure you bind your value. mysqli does not automatically
secure your query
$connection= mysqli_connect($host, $user, $password, $database);
$query="SELECT prs_amtdb FROM prs WHERE prs_amtcrck = 0";
$result= mysqli_query($connection, $query);//$connection is your database
//connection
//fetch the result
while($row= mysqli_fetch_array($result)){
echo $row['column_name'].'<br/>';
}
Using PDO:
$query = $db->query("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = 0");
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
http://php.net/manual/en/pdo.query.php
If you have user input that you're using in your query you should always use prepared statements eg:
$query = $db->prepare("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = :atmcrck");
$query->bindParam(':atmcrck', 0); // 0 will be the user input
$query->execute();
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
Make sure you have a database connection setup in PDO:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
die($e->getMessage());
}
http://php.net/manual/en/pdo.connections.php
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");
?>
I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);
Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>