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.
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 website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES ('.$_SESSION['user_name'].')';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error message:
Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16
Tried a bunch of things but can't figure it out. What is wrong here?
You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES (?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Before you use any $_SESSION variables you need to call session_start().
Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.
If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub
I'm following a tutorial on the net on PHP and MySQL.
I'm using Linux. I'm trying to establish a connection to a database but it is not working.
I have my database:
create database test;
create table user(name text, pass text);
insert into user values('john', '123');
and then my php:
<?php
$_host = "localhost";
$_dbuser = "root"
$_dbpass = "";
$_dbname = "test";
#mysql_connect("$_host", "$_dbuser", "$_dbpass") or die("could not connect");
#mysql_select_db("$_dbname") or die("no database");
echo "connection stablished";
?>
And the output of my file is just a blank tab on the browser.
What should I do to solve this? What am I doing wrong?
Thank you in advance. I'm very new to web programming.
$_host = "localhost";
$_dbuser = "root"
$_dbpass = "";
$_dbname = "test";
$link = mysqli_connect($_host, $_dbuser, $_dbpass, $_dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo "connection stablished";
Now...
Use mysqli_* functions as mysql_* are deprecated.
You will need $link variable later for queries.
As you're newbie read this: How can I prevent SQL injection in PHP?
Prepared statements FTW! Remember!
I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.
I am using WebMatrix Beta 3 which has support for php 5.2 and 5.3 I am able to run php pages but when I am trying to connect to mySql DB its not working.
Can anyone please suggest me the right way of doing it.
The connection code is written in a file called dbinfo.php which resides under config folder
<?php
$hostname = '127.0.0.1';
$username = 'root';
$password = 'password';
$database = 'test';
$link = mysql_connect($hostname, $username, $password)
or die("Could not connect : " . mysql_error());
mysql_select_db($database) or die("Could not select database");
//Below function added to allow customized unescaping.
function mysql_unescape($sRet_VAL=""){
$sRet_VAL = str_replace('\"','"',$sRet_VAL);
$sRet_VAL = str_replace("\'","'",$sRet_VAL);
return $sRet_VAL;
}
?>
and I am using this file as follows
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/config/dbinfo.php');
?>
<?php
$query = "SELECT * from temp";
$result = mysql_query($query)
or die("Error: " . mysql_error());
?>
it worked seems like webmatrix do not recognize I replaced it wilt <>php echo $varData ?> and it worked.