Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a problem with my sql request in my php. I try to use the "query" but when I do a "fetch" I get an error. I know this error is because of my sql request but I can't find the problem.
my php code :
$host = 'localhost';
$dbName = 'appliderencontre';
$username = 'root';
$pswd = '';
try
{
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e;
}
$requete = "SELECT pseudo FROM user";
$reponse = $db-> query($requete);
while($donnee = $reponse->fetch()){
echo $donnee['pseudo'];
}
$reponse ->closeCursor();
And that is my error :
I need your help, i can't find anything for helping me.
Thanks a lot !
(Sorry for my english, i'm a begginer).
Change this code :
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
to
$db = new PDO("mysql:host=" .$host .";dbname=" . $dbName, $username, $pswd);
because dbname must be lower-case.
Try to run this code and use PDO::FETCH_OBJ in the fetch function.
$host = "localhost";
$user = "root";
$password = '';
$dbname = "appliderencontre";
try {
$dns = "mysql:host=".$host.";dbname=".$dbname.";charset=utf8";
$pdo = new PDO($dns, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "PDOError: " . $e->getMessage()." In ".__FILE__;
}
$query = 'SELECT pseudo FROM user';
$query = $pdo->query($query);
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
echo $row->pseudo;
echo '<br>';
}
My programming level is fairly elementary so a 'coding for idiots' type of explanation would be great...
I have the following code:
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$db_name = 'db_name';
$connect = mysqli_connect($host, $user, $password);
mysqli_select_db($connect, $db_name) or die ("Couldn't connect");
function roll_die() {
$throw = rand(1, 6);
return $throw;
}
function get_subtotal() {
$query = "SELECT * FROM throws";
$result = mysqli_query($connect, $query);
while ($row = $result->fetch_assoc()) {
echo $row['value']."<br>";
}
}
?>
I get an error because the '$connect' in the function subtotal() is apparently undefined. How can that be if it's defined at the top of the page? Wouldn't that make it a global function?
Please don't just give me the correct code to fix this. Could you explain what's going on and how PHP defines and stores variables?
Thanks!
Ok, I found the answer.
At the top of the page:
$connect = mysql_connect($host, $user, $password);
Then within the function:
global $connect;
Actually, I found the answer in another question which was essentially asking the same thing, so apologies for the repost.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In previous projects, I use the following code to connect to MySQL database:
File: connect.php
define('DB_SERVER','my_server');
define('DB_DATABASE','my_database');
define('DB_SERVER_USERNAME','my_user');
define('DB_SERVER_PASSWORD','my_password');
$db_server = DB_SERVER;
$db_username = DB_SERVER_USERNAME;
$db_password = DB_SERVER_PASSWORD;
$db_database = DB_DATABASE;
$connection = mysqli_connect($db_server, $db_username, $db_password,$db_database);
if ($connection) {
//Connected OK
} else {
die ("Cannot connect to database $db_database in $db_server!");
}
And all my other scripts looks like the next:
include "connect.php"
//From here, I can use the $connection variable to select/insert/delete/update data in my_database.
Now, I'm trying to use a more OOP approach in my programming, then I create the next code to connect to MySQL:
Class Connection extends mysqli{
public function __construct(){
if ($config = parse_ini_file('config/config.ini',true)){
$server = $config['database']['server'];
$username = $config['database']['username'];
$password = $config['database']['password'];
$database = $config['database']['dbname'];
parent::__construct($server,$username,$password,$database);
if (mysqli_connect_error()){
$message = "Conection error (" . mysqli_connect_errno() . ") " .
mysqli_connect_error();
throw new Exception($message);
}
} else {
$message = "Config file not found.";
throw new Exception($message);
}
}
}
And my scripts now looks like:
set_include_path(__DIR__.'/Classes');
spl_autoload_extensions(".php");
spl_autoload_register();
try {
$connection = new Connection();
} catch (Exception $ex){
die($ex->getMessage());
}
//Again, from here I can use the variable $connection to use my database
Both solutions works, but...
The questions are:
Is this necessary or am I overcomplicating these scripts?
Are there best practices in this concerns?
Thanks in advance for any comments to improve all of this.
config.php:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'databasename'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
database.class.php:
<?php
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM database');
$query->execute();
return $query->fetchAll();
}
}
?>
index.php:
<?php
require_once 'config.php';
require_once 'database.class.php';
$db = new database($pdo);
$rows = $db->getData();
?>
I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
EDIT 01
$servername = "localhost";
$username = "root";
$password = "";
To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:
MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
Password.
Database name. This is the MySQL database name you want to connect to.
Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
Socket name. Specifies the socket or named pipe that should be used.
Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.
Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.
On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.
Why use mysqli? Just use PDO for safer mysql connection just use:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
You should specify hostname
$con = mysqli_connect("localhost","username" ,"password","databasename");
If it returns an error like
Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Replace localhost with 127.0.0.1.
If still you cant connect check if mysql server is actually running.
service mysqld start
Then, try the one of the following following:
(if you have not set password for mysql)
mysql -u root
if you have set password already
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
#session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
A better method is to keep the connection and the login parameters apart.
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
This in combination with a database factory keeps the data separated and clean.
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
After that you can easily make your (class based) your CRUD classes (objectname+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
And with this fine coding it's a piece of cake to select items in frontend:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
The easiest way to connect to MySQL server using php.
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
localhost like this (MySQLi Procedural)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}
what is the best way to connect PHP application on MySQL.
So far I had the below connection classes.
class Connection{
private static $server = "127.0.0.1";
private static $catalog = "schemadb";
private static $username = "rootuser";
private static $password = "password";
public static $current = null;
public static function Open(){
self::$current = mysqli_init();
if(!self::$current){
die("Failed to initialize connection");
}
if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
die("Cannot connect to server");
}
return self::$current;
}
public static function Close(){
self::$current->close();
}
}
and also I have
abstract class abstractDAO
{
protected function getConnection()
{
$mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
return $mysqli;
}
}
or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..
You can try using the PDO object:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Have a look at PHP PDO documentation page
Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate.
You just need to enter your database configuration like give in below
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';
You can connect through data using PDO, here is an example
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
try {
$conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$stmt = $conn->prepare("SELECT * FROM todolist");
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table border="1" align="center">
<tr>
<th>name</th>
<th>type</th>
<th>status</th>
</tr>
<?php
foreach($stmt->fetchAll() as $k=>$v){
echo
"<tr>
<td>{$v['name']}</td>
<td>{$v['type']}</td>
<td>{$v['status']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>
try this
<?php
$user = $_POST["username"];//if this doesnt work try the next line
$user = (isset($_POST["username"]) ? $_POST["username"] : "");
$host = "localhost";//mysql password
$username = "";//mysql username
$password = "";//mysql password
$db_name = "database";//database name
$tbl_name ="test";//table name
//make the connection
$con = mysql_connect("$host","username","password")or die("Could not connect.");
$conn = mysql_select_db("$db_name")or die("Could not select database.");
$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
//query mysql
$result = mysql_query($sql);
if($result){
//if it works show this
}else{
//if it doesnt work show this
}
?>
ive tryed a lot of times to make a connection to a database and i finaly found one.