Im trying to insert data into mysql database.
I have class connection
class connection{
function __construct(){
$servername = 'localhost';
$username = 'root';
$password = '';
$database='products2';
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
echo "succesful connection!</br>";
$this->query=$conn;
return true;
}
}
}
And another class in witch I try to insert data into database(i try to do this in __construct of that class)
$sql="INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db=new connection();
$result=$db->query($sql);
However I get this errror:
Fatal error: Call to undefined method connection::query() in ....
In order to use the query (from mysqli class) method you need to create a new method public function query() {}. This method will be able to use the mysqli method. In the end, you will be able to acheive the same result but by applying 'query' on your own object ($db) like so $result = $db->query($sql);
Here's the class :
<?php
class connection{
// define a variable for the database connection
private $conn;
// when an instance of 'connection' class is created a connection is made through mysqli
public function __construct()
{
$servername = 'localhost';
$username = 'root';
$password = '';
$database='products2';
// the connection is stored inside the private variable
$this->conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
return false;
} else{
echo "succesful connection!</br>";
return true;
}
}
// method used to send a query to database
public function query($sql)
{
// here you use the connection made on __construct() and apply the method query. Basically we are using inside our method (called query) a method (call query too) from the mysqli class
$this->conn->query($sql);
return true;
}
}
Calling the method :
<?php
// prepare the SQL request
$sql = "INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
// create a new instance of the class connection
$db = new connection();
// run the method $sql on the newly created instance $db
$result = $db->query($sql);
Because in your last line - $result = $db->query($sql); - you are trying to call a function named 'query'. If you look inside your connection class the only function you have is the constructor.
To fix this you are going to need to add a function called "query" (note this is not an ideal name for the function).
Here is some commented code (not guaranteed to be error free!)
class connection{
protected $conn; // add conn so that you can use it later
function __construct()
{
$servername = 'localhost';
$username = 'root';
$password = '';
$database='_mvc';
// Assign $this->conn to a database object
$this->conn = new mysqli($servername, $username, $password, $database);
// Remember we are checking >>THIS<< conn now
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
return false;
}else{
// no need to assign anthing here as the database object has already been assigned to $this->conn
echo "succesful connection!</br>";
return true;
}
}
// here is the missing function
public function query($sql) {
// now we are accessing the database objects query method and massing the SQL
return $this->conn->query($sql);
}
}
$sql =
"INSERT INTO products (name,price,category,f_material,f_size)
VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db = new connection();
$result = $db->query($sql);
I would recommend you jump straight into php data objects and be done with it because PDO is the best 'standard' way to access databases these days.
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I have the dbc.inc.php file. inside of it there are connect function that connects me to the DB.
In the test.inc.php file i have the runQuery function inside of a "Test" class. The "Test" class extends from the "Dbc" class allocated in the dbc.inc.php file.
The runQuery($db, $sql) runs query. But if error happend or warning he is not showing the error. i belive that im having a syntax mistake.
For the testing interesst i have given the wrong fieldname in my $sql statment. The error is hapenning but is not showing.
dbc.inc.php
<?php
class Dbc{
private $serverName;
private $userName;
private $password;
protected function connect($dbName = NULL){
$this->serverName = "localhost";
$this->userName = "root";
$this->password = "";
$conn = new mysqli($this->serverName, $this->userName, $this->password, $dbName);
if (!$conn) {
die("<h3>Error Connecting to the Database.</h3><h4 style=\"color: red\">". $conn->connect_error . "</h4>");
} else {
return $conn;
}
}
}
?>
test.inc.php
<?php
require 'dbc.inc.php';
class Test extends Dbc{
function runQuery($db, $sql){
$query = mysqli_query($this->connect($db), $sql);
if (!$query) {
echo "no Query";
echo $this->connect($db)->connect_error;
return 0;
} else {
echo "Query EXEC";
return 1;
}
}
}
?>
The test code
$conn = new Test;
$conn->runQuery("tch_phn", "UPDATE `employee` SET `uiS`='Assad' WHERE `uid`='Assad' ");
The error is i have given a unknown field name (uiS has to be uid). How can i do this?
You don't need the Dbc class. It is not useful to you at all at its current state. The mysqli connection is always the same three lines of code and there is no point to add a class for it.
To connect to DB using mysqli use:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name');
$mysqli->set_charset('utf8mb4'); // always set the charset
Then you can write a class which will take the DB connection as a parameter in __construct().
class Test {
private \mysqli $db = null;
public function __construct(\mysqli $db) {
$this->db = $db;
}
function runQuery($sql) {
$query = $this->db->query($sql);
}
}
That's it. Although you really should try to create a more useful mysqli abstraction class, or even better, use PDO instead. If you want to write mysqli wrapper class you can start with the following idea (adjust to your needs):
class DBClass extends mysqli {
public function __construct($host = null, $username = null, $passwd = null, $dbname = null, $port = null, $socket = null) {
// Enable error reporting and call mysqli constructor
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
$this->set_charset('utf8mb4'); // always set the proper charset which should be utf8mb4 99.99% of the time
}
public function safeQuery(string $sql, array $params = []): ?array {
// Prepare statement:
$stmt = $this->prepare($sql);
// If the statement has parameters then bind them all now
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
// Execute it and get results if there are any
$stmt->execute();
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
// If the query was INSERT or UPDATE then return null
return null;
}
}
Then you can execute any SQL statement with a simple one line even when using mysqli.
i'm updating from PHP5.6 to PHP7.0 and this doesn't work anymore:
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff()
{
function GetSomeDate()
{
$result=mysqli_query($con, "SELECT * FROM my_table");
}
}
Looks like the $con variable is not available inside the class.
Do i have to to something like this?
global $con=mysqli_connect()
Thanks!
The main pattern used is something like, pass database connection into constructor (dependency injection) and then store it in an instance variable ($this->con in this case). Then later database calls just use $this->con for the database connection...
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff
{
private $con;
// Create instance with connection
public function __construct( $con ) {
// Store connection in instance for later use
$this->con = $con;
}
public function doSomething() {
// Run query using stored database connection
$result=mysqli_query($this->con, "SELECT * FROM my_table");
}
}
// Create instance, passing in connection
$some = new DoSomeStuff ($con);
$some->doSomething();
heres something I've worked with recently
class Database {
private $_conn = null;
public function getConnection($password) {
if (!is_null($this->_conn)) {
return $this->_conn;
}
$this->_conn = false;
try {
$this->_conn = new PDO("mysql:host=localhost;dbname=databasename", 'root',
$password);
$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $this->_conn;
}
}
function conOpen() {
$servername = "localhost";
$username = "root";
$password = "password";
$db = new Database();
$conn = $db->getConnection($password);
return $conn;
}
Then use it like this
$con = conOpen();
You can check out PDO connection here
I'm trying to use db connection parameter inside function, i tried to global it but it does not working.
$host = 'localhost';
$username = 'b**s';
$password = '1******m';
$dbname = 'b*********e';
$connection = new mysqli($host, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
When i'm executing the query it returning error, becuase i didn't pass $connection parameter inside function.
function insertData(){
{......}
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
}
Can anyone guide me what is best to use without passing parameter inside function. I would like to appreciate if someone guide me.
In your function you should do something like
global $connection;
then use it below like
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
This is well documented in manual, i suggest you go have a look.
Create a database class and access it by object
<?php
class Database {
private static $db;
private $connection;
private function __construct() {
$this->connection = new MySQLi(/* credentials */);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if (self::$db == null) {
self::$db = new Database();
}
return self::$db->connection;
}
}
?>
Then just use $db = Database::getConnection(); wherever I need it.
So, I'm in the middle of writing a web application for one of my clients, and I've decided to keep the database connection in a class. The following code is what I have:
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
}
I am using the standard PHP function of mysqli_query to send queries to the database. I am using the following to send queries to the database:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->$connection, 'QUERY');
}
I'm new to using classes in my code. I'm still learning, as we all are. I've checked about but cannot find a fix for my issue. I know what the issue is: it's an issue with the class being an object, and something to do with fetching the returned $connection variable from it.
How can I fix this issue so that I can connect correctly to my database? Also, could anyone point me in the direction of some documentation that I could learn the fix so I can tackle this in future.
Thank you!
There are a lot of different ways you could write a object to handle connections and queries to the database.
What matters most is what your trying to achieve.
I would think these would be a few features you would like to have.
Single Connection
Runs SQL and returns mysqli results.
Access to the connection for escaping values.
It looks like you want to store your credentials within the object it self. ( I would suggest passing these in as a value in __construct()
These are a few basic features, that could easily be expanded apon.
class databaseConnection {
//private $hostname = 'hn.app.dev';
//private $username = 'root';
//private $password = '';
//private $database = 'hn_app_dev';
private $connection; // this is where the object will store the connection for other methods to access it
public function __construct($host, $username, $password, $database)
//public function connect() {
$this->connection = mysqli_connect($host, $username, $password);
if ($host) {
$this->connection->select_db($database);
if (!$this->connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
// this is so databaseConnection $db can access the connection for escaping MySQLi SQL
public function connection(){
return $this->connection;
}
function fetch_from_db($query) {
//$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
//$query = mysqli_query($connection->$connection, 'QUERY');
$query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
return $query; // return the results to the $results var in the bottom example
}
// this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
function __destruct(){
$this->connection()->close();
}
}
// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';
// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);
// print the results
while($result = $results->fetch_assoc()){
print_r($result); // print_r on each row selected from db
}
You can learn more about OOP and PHP Objects in the Manual and there are many tutorials available online about specifically classes to manage database connections and queries.
http://php.net/manual/en/language.oop5.php
Hope this helps!
If you're going to keep it in a class, you never call the connect() function. But if you want it connected when you initiate the class, change the connect() function to __construct() and remove the return and assign it to a public variable.
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public $connection;
public function __construct() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
$this->connection = $host;
}
}
}
After that, you can get the database connection in your function like:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->connection, 'QUERY');
}
Now, after having said all that, you don't want to create a new instance in every function to access the database. So possibly making it static and create an init() function of sorts so it takes less memory in the overall application.
For class documentation PHP's Classes/Objects page will help. Specifically the 'Examples' link.
<?php
class databaseConnection {
private $hostname = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'onlinylh_sggsfaculty';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
if ($host) {
return $host;
}
else{
echo "Error";
}
}
}
function fetch_from_db($query) {
$conn = new databaseConnection();
$r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>
This Worked For me.
I am creating a php restful API and currently I have the database connection information in each function.
//Connect To Database
$hostname=host;
$username=username;
$password=password;
$dbname=dbname;
mysql_connect($hostname, $username, $password) OR DIE('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
mysql_query($sqlApiAccess) or die('Error, insert query failed');
What is the best way of doing this, Can I have one database connection per php file? Or do I need to do it per function that uses the database.
To avoid creating a new database connection each time, we can use Singleton design pattern-
we need to have a database class- to handle the DB connection-
Database.class.php
<?php
class Database
{
// Store the single instance of Database
private static $m_pInstance;
private $db_host='localhost';
private $db_user = 'root';
private $db_pass = '';
private $db_name = 'databasename';
// Private constructor to limit object instantiation to within the class
private function __construct()
{
mysql_connect($this->db_host,$this->db_user,$this->db_pass);
mysql_select_db($this->db_name);
}
// Getter method for creating/returning the single instance of this class
public static function getInstance()
{
if (!self::$m_pInstance)
{
self::$m_pInstance = new Database();
}
return self::$m_pInstance;
}
public function query($query)
{
return mysql_query($query);
}
}
?>
& we can call it from other files-
other.php
<?php
include 'singleton.php';
$pDatabase = Database::getInstance();
$result = $pDatabase->query('...');
?>
Create a config.php And add the code:
config.php:
$hostname = 'host';
$username = 'username';
$password = 'password';
$dbname = 'dbname';
$conn = mysqli_connect($hostname, $username, $password) OR die('Unable to connect to database! Please try again later.');
mysqli_select_db($conn, $dbname);
Then in any file you wish to use mysql, add the following:
script2.php
<?php
require_once 'config.php';
mysqli_query($sqlApiAccess) or die('Error, insert query failed');
?>
There is no need to make connection in each function. you need to make a connection file like conn.php and make the connection queries.
<?php
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
?>
in any other file where you want to connect database just write this line
<?php include("conn.php");?>
On this file you are able to run any query.
do this:
$db_connection= mysql_connect($hostname, $username, $password) OR DIE('Unable to connect to database! Please try again later.');
And every time you want to query:
mysql_query("my_query",$db_connection);
Note, if you connect to the DB in a function, you will need to global $db_connection.
And when you want to close the DB connection:
mysql_close($db_connection);
Why won't you move out the connection information into config and the call to mysql_connect into some factory?
E.g.
class ConnectionFactory {
public static MysqlConnection CreateConnection() {
$connection = mysql_connect(Config::$host, Config::$port etc);
mysql_select_db($connection, Config::$schema);
return $connection;
}
}
and then in your code
$connection = ConnectionFactory::CreateConnection();
mysql_query($connection, $sqlApiAccess) or die('Error, insert query failed');