Using the following code, the database can be connected to successfully. However, when trying to execute a query using the function 'executeNonQuery' I get the error { Access denied for user ''#'localhost' to database 'photobook' }. The user has full privileges, although strangely the query 'show grants' will not display that fact. However, when looking at user privileges in the GUI of mysql workbench it is. What can be the problem? I even used root, but the query is denied with the same error. The user can connect, but can't issue a query.
file: class.database.php
<?php
class Database {
function __construct(){
}
public function connect($host, $user, $pass){
$dbcnct = mysqli_connect($host, $user, $pass);
if(!$dbcnct){
die("Couldn't Connect: " . mysql_error());
}else{
echo "Connected Successfully";
}
}
public function disconnect(){
mysql_close($dbcnct);
if(!$dbcnct){
echo "Disconnected Successfully";
}
}
public function executeNonQuery($database, $sql){
mysql_select_db($database);
$retval = mysql_query($sql, $dbcnct);
if(!$retval){
die("Couldn't Update Data: " . mysql_error());
}
echo "Update Successful";
}
}
?>
<?php
include 'class.database.php';
$db = new Database;
$db->connect("localhost", "user", "pass");
$userdata=$_GET['data'];
$index=$_GET['index'];
echo $index . "<br/>";
foreach($userdata as $data){
$sql = "update photobook set photoName='" . $data . "' where photoPosition=" . $index;
$db->executeNonQuery("photoBook", $sql);
echo $data . "<br/>";
}
$db->disconnect();
?>
Your $dbcnct variable is only defined for the function where you use it, not the whole class. You need to use class variables so you can share variables throughout the different functions :
<?php
class Database
{
public $dbcnct;
function __construct()
{
// Nothing
}
public function connect($host, $user, $pass){
$this->dbcnct = mysqli_connect($host, $user, $pass);
if(!$this->dbcnct){
die("Couldn't Connect: " . mysql_error());
}else{
echo "Connected Successfully";
}
}
public function disconnect(){
mysql_close($this->dbcnct);
if(!$this->dbcnct){
echo "Disconnected Successfully";
}
}
public function executeNonQuery($database, $sql){
mysql_select_db($database);
$retval = mysql_query($sql, $this->dbcnct);
if(!$retval){
die("Couldn't Update Data: " . mysql_error());
}
echo "Update Successful";
}
}
?>
Now all you need to do is :
$database->connect("host", "user", "pass");
$database->executeNonQuery("database", "sql");
But first of all you need to fix the mysql_ and mysqli_ mixups :)
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
CREATE USER 'a_project'#'%' IDENTIFIED BY 'password';
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON a_database.* TO 'a_project'#'%';
i suggest you keeping $dbcnct as a variable in the database class so that when you call function executeNonQuery,the mysql connection won't be lost.
Put your connect script in the __construct() section, this initialize connection to call new Database; and make available to all functions in the Database Class without request new connection every time you run a query.
Related
I'm trying to connect to a database using a config file that is a part of my Joomla website.
My config file looks like:
<?php
class JConfig {
public $dbtype = 'mysqli';
public $host = 'localhost';
public $user = 'xxxx';
public $password = 'xxxx';
public $db = 'xxxx';
public $dbprefix = 'xxxx_';
}
Below is the page that includes the configuration file:
<?php
include("configuration.php");
// Create connection
$conn = mysqli_connect($host, $user, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, navn, email FROM XXXX";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["navn"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
However, I cannot connect to the database as I get the following error message:
Connection failed: Access denied for user ''#'localhost' (using password: NO)
I think the issue might be because the config file has public in front of all the variables.
Question: How can I get around keeping the variables public, since the Joomla script needs them, but avoid the error?
Assuming the path is correct, do this instead:
require_once "configuration.php";
$Conf = new JConfig;
// Create connection
$conn = mysqli_connect($Conf->host, $Conf->user, $Conf->password, $Conf->db);
In simple terms the config file contains an class named JConfig, so you must instantiate that class and access it's public properties.
other stuff
Use require not include, as this config is needed for the rest of this script to work and include will just ignore missing files. Require will produce an error, and let you know what is wrong when the file is missing/no found. Further, use require once because you cannot redefine the same class multiple times.
PS. you don't need the () on include/require, and the same is true for construct with no arguments... (I'm lazy so I don't like to type those things out)
Enjoy!
I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);
you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');
I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql
I created a class to access my database. The simplified class is following (I named it dbaccess.php)
class dbaccess {
function read($db) {
$con = mysqli_connect($db);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM equipment");
while($row = mysqli_fetch_array($result)){
$print = $print . $row['ID'] . " " . $row['name'] . " " . $row['new_price'] . " " . $row['residual_value'] . "<br>";
}
echo $print;
mysqli_close($con);
}
}
To access the class, I use this code
include './dbaccess.php';
//define db address
$add = '"localhost","myuser","mypassword","mydbname"';
$db = new dbaccess;
$db->read($add);
This code resulting
Failed to connect to MySQL: Unknown MySQL server host '"localhost","myuser","mypassword","mydbname"'(2)
I don't know how to fix it, can anyone here help me?
You're passing a single string to mysqli_connect. You need to pass "localhost", "myuser",... as separate variables.
http://php.net/manual/en/function.mysqli-connect.php
I have something similar with yours, download my files from dropbox and have a look inside
DB Connect
class dbaccess {
function read($db) {
$con = mysqli_connect($server, $user, $password, $dbname);
(...)
Then in your code, you should divide the parameters.
include './dbaccess.php';
//define db address
$db = new dbaccess;
$db->read("localhost","myuser","mypassword","mydbname");
REF
It's probably a better idea to store your host, username, password and database in separate variables like this:
$host = "localhost";
$user = "myuser";
$pass = "mypassword";
$data = "mydbname";
$db = new dbaccess(); // <-- It's good practice to use parentheses in the constructor statement.
$db->read($host,$user,$pass,$data);
And then the implementation of your dbaccess class could be more like this:
$con = mysqli_connect($host,$user,$pass,$data);
This is because the mysqli_connect function takes the host, username, etc. as separate parameters, not as a single string.
Does anyone know to give my user account access to a table? I connect to the database fine but when I try to select the table it tells me Access denied for user 'dboxxxxx'#'%' to database.
I'm using basic php code
$con = mysqli_connect('xxxxxx.db.1and1.com', 'xxxxx', 'xxxxxx');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
else {echo 'success!';}
$selected = mysqli_select_db($con,'userTable');
if(!$selected){
die ('cannot use db: '.mysqli_error($con));
}
There is no permissions options on the 1and1 phpmyadmin that I can see unless I'm totally missing it. Anyone have any ideas?
First of all, you need to supply dboxxxxx as a username, not 'dboxxxxx'#'%'
Are you running this code localy or within your server? The 1und1 firewall blocks connections from the foreign networks
You're probably not making the connection to the database correctly.
Try the changes I made. Note that I do not know that you are using classes and functions.
UPDATE
$mysqli = new mysqli('xxxxx.db.1and1.com', 'xxxx', 'xxxx','xxxx');
if(mysqli_connect_errno ())
{
printf('Unable to connect to database ' . mysqli_connect_error());
}
else
{
$stmt = $mysqli->stmt_init();
if(!$stmt)
{
echo "init failed";
}
else
{
$cmd = "insert into `userTable` (`oauthtoken`,`oauthtokensec`,`userid`,screenname`) VALUES ('?','?','?','?')";
if($stmt->prepare($cmd))
{
$stmt->bind_param('1','1','1','1');
$stmt->execute();
echo $stmt->affected_rows . " Row(s) Inserted";
$stmt->close();
}
else
{
echo "Prepare Failed";
}
} $mysqli->close();
}
<?php
$cons=mysql_connect("localhost","root","");
mysql_select_db("infogallery") or die('Not Connected to the data base:'.mysql_error());
?>
I write above code for connection with mysql but when i run this scripts..nothing display on the brouser...what can i do for the connection with mysql....
If nothing is displayed, then it means it succeeded. Add more code which queries the database and displays some results.
Don't connect as the root account. Create an account specifically for playing around with.
Once you've done that, modify your code as follows:
$cons = mysql_connect('localhost', 'username', 'password');
if ($cons === FALSE) {
die("Failed to connect to MySQL: " . mysql_error());
}
mysql_select_db(etc.....);
You don't check if the connection failed, then try to do a database operation on that potentially failed connection. The or die(...) you have will only show the error caused by the select attempt, and the error message from the failed connection will be lost.
I like to just do
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("infogallery") or die(mysql_error());
echo "So far, so good.";
How about something like the following:
<?php
try {
$cons = mysql_connect("localhost","username","password");
} catch ($e) {
die('Failed to connect to the database: ' . mysql_error());
}
try {
mysql_select_db("infogallery", $cons);
} catch ($e) {
die('Failed to select the database: ' . mysql_error());
}
?>