Errror recovering mysql data with php - php

i had installed freestyle extension in joomla (to allow php code in articles) im trying to access to a database in mysql with the next code
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
$sql = "SELECT id, nombre, edad
FROM Prueba";
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf('%s <br/>', $r['nombre']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
And i get this error in the article and i dont know why this is happening
Parse error: syntax error, unexpected T_VARIABLE on line 13

$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
should be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
(You're missing a ';')
Also I think your code isn't going to work exactly as planned since your SQL has no variables but you attempt to pass one to $q->execute() but I'm sure you can sort out what you're trying to do yourself...

Related

PHP error from bind param [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm new to PHP but here's my code, and I'm getting :
Fatal error: Uncaught Error: Call to a member function bindParam() on boolean
I have tested and test, not sure what is going wrong, some pointers would really help to move on - thanks in advance.
$url_slot = parse_url($str);
$urlArray = explode('/',$url_slot['path']);
$passid = $urlArray['11']; // serial no
$deviceId = $urlArray['8'];
$passtype = $urlArray['10'];
$servername = "host";
$username = "user";
$password = "******";
$dbname = "db";
try {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES
(:device_id,:pass_id,:pass_type,:created,:modified)");
$stmt->bindParam(':device_id',$device_id);
$stmt->bindParam(':pass_id',$pass_id);
$stmt->bindParam(':pass_type',$pass_type);
$device_id = $deviceId;
$pass_id = $passid;
$pass_type = $passtype;
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO Devices (push_token) VALUES
(:push_token)");
$stmt->bindParam(':push_token',$push_token);
$push_token = $content['pushToken'];
$stmt->execute();
$conn = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any help would be great.
Whenever you get a Fatal error for sending the wrong type to a function, print the arguments you are trying to pass on the guilty line.
Whenever the wrong type in question is a boolean, check if you wrote tests for every function return that could hurt your program if the function had failed, because a variable that contains a boolean when it shouldn't usually does because the function that gave you that value failed and returned false.
In your case, it's even more simple : The error doesn't tell you that you try to pass a boolean to a function that awaits another type, it tells you that you try to call the method bind_param(), which means that you treat a boolean as an object.
$stmt->bindParam(':device_id',$device_id);
Therefore, it is $stmt which is empty.
$stmt = $conn->prepare("INSERT INTO Registrations (device_id, pass_id, pass_type) VALUES (:device_id,:pass_id,:pass_type,:created,:modified)");
The function that returns you the value you assign to $stmt being that one, I advise you to test if $stmt is different from false right after setting it, and to print the error type and message from $conn if it isn't.
In addition to that, I get the feeling that you aren't yet accustomed to work with API, you seem to lack some experience and are also trying to use PDO exceptions while working with MySQLi. Maybe you should spend some time reading their respective docmuentations.
Stack Overflow is also filled with various questions and docs regarding both.

How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

PDO does not return error even when setting error mode

EDIT: The problem is that the errors are not being displayed. This is just to clarify everyting.
I just learned what a PDO is, and I decided to test how it works. From the tutorials I've checked, you have to use the following line to display errors: $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So anyways, I used this line, made sure that my query had an error and it still didn't display any errors. The connection to the database works, it always returned me an error when it couldn't connect. Anyways, here my code:
<?php
// Connection to the mysql database using PDO
$mysql_host = "hidden";
$mysql_dbname = "hidden";
$mysql_username = "hidden";
$mysql_password = "hidden";
try {
$DBH = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->prepare("SELECT username FROM username");
} catch (PDOException $e) {
echo "Error connecting to the database:" . $e->getMessage();
}
?>
You don't get any errors because
$DBH->prepare("DELETE use FROM blob");
doesn't execute, only prepares a query to be executed.
Replace that line of code with:
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
You need to execute it
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
Otherwise it doesn't actually run the query.

Can i use multiple databases in one applicationin php?

I am Developing the simple application,the application related to database operations.
My doubt is how can i connect to multiple databases same time.
how can php knows which databases the data will store.
If the user enter the data which database it will enter,both databases or one database.
Please answer my question.i have struggling a lot for this question.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
Yes you can.. by using two connection strings..
$mysqli1 = new mysqli('HOST1', 'USER1', 'PASSWORD1', 'DB_NAME1');
$mysqli2 = new mysqli('HOST2', 'USER2', 'PASSWORD2', 'DB_NAME2');
and your queries should be like
$result1 = $mysqli1->query('query ......');
and
$result2 = $mysqli2->query('query ......');
Of course you can given example below add more connections if you want:
Class database
{
private oracleDatabase;
private mysqlDatabase;
public function connOracle() {
$db = "";
$user = "";
$password = "";
try {
$this->oracleDatabase = new PDO("oci:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Oracle). ". $e->getMessage();
}
}
public function connMysql() {
$db = "";
$user = "";
$password = "";
try {
$this->mysqlDatabase = new PDO("mysql:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Mysql). ". $e->getMessage();
}
}
}
Be carefull if you are using two databases on the same server at the same time. By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do
<?php
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
?>
then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !
You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
Use this below link to refer.What you have asked here.
PHP Documentation
Yes, you may use multiple database in one application, but the main thing is when you are communicating with the dbname, you have to specify that dbname also so than script will communicate with only that db in which you had defined. Ex.
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
$resultsa = mysql_query('SELECT * FROM table_a', $dbname) or die('Could not query database_a');
Yes you can connect multiple databases.
open your php.ini file and give me your database details like
port number,username,password.
And after that you can give the queries like this in your applications
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
Then to query database 1, do this:
mysql_query('select * from tablename', $dbh1);
and for database 2:
mysql_query('select * from tablename', $dbh2);
i think this is work fine for your question.
Yes you can, in very basic terms, you do it like this:
http://au1.php.net/function.mysql-connect
$conn = mysql_open($host, $username, $password, true);
To connect to multiple databases on the same server:
$dblink1 = mysql_select_db('database_a', $conn);
$dblink2 = mysql_select_db('database_b', $conn);
To get results from two databases:
$resultsa = mysql_query('SELECT * FROM table_a', $dblink1) or die('Could not query database_a');
$resultsb = mysql_query('SELECT * FROM table_b', $dblink2) or die('Could not query database_b');
edit - keep in mind that the mysql_ functions aren't available in recent PHP releases because they've been removed.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.

Call to a member function query() on a non-object on trying to read data

Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?

Categories