I have installed WAMP server on my local machine and I have written php script to insert record into the database, but I'm getting the following error-
Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in C:\wamp\www\test_services\db_connect.php on line 32
following is my db_config code
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "test_db"); // database name
define('DB_SERVER', "localhost"); // db server
?>
Here is my **db_connect.php code**
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT
{
// constructor
function __construct()
{
// connecting to database
$this->connect();
}
// destructor
function __destruct()
{
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect()
{
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close()
{
// closing db connection
mysql_close();
}
}
?>
Please help.. Thank you..!
I don't think you are showing the correct file. The problem is in db_connect.php. It is very likely that that file does not include db_config.php, i.e:
require_once 'path/to/db_config.php';
Edit: Does db_config.php actually live in the same directory as db_connect.php? Your code suggests that it does, which may be incorrect?
Edit: What happens if you put $var = 'hello' in db_config.php, and then print $var in db_connect.php after you include it, do you see 'hello'? Just to clarify you are connecting with the file..
Related
my question is about connect with mysql database in other server by php ??
Server A is rec.misuratau.edu.ly, Server B is alrand.ly , I need to code pls.
I am not sure if I understand well. You are asking how to make a connection to mysql database on two different server?
You can do it like this:
First create databases on server, create user define password and grant access to the user.
Create two separate file: First is Config.php
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'http://rec.misuratau.edu.ly'); // replace with servername
define('DB_NAME', 'db');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
Second is DbConnect.php
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect() {
include_once dirname(__FILE__) . '/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($this->conn,"utf8");
// returing connection resource
return $this->conn;
}
}
LAter you just call the method before sql statements.
Please check the link below as well:
https://www.w3schools.com/php/php_mysql_connect.asp
Below is my sample code for my PHP program, and my database has already been created.
createteam.php:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//getting values
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
//including the db operation file
require_once '../includes/DbOperation.php';
$db = new DbOperation();
//inserting values
if($db->createTeam($teamName,$memberCount)){
$response['error']=false;
$response['message']='Team added successfully';
}else{
$response['error']=true;
$response['message']='Could not add team';
}
}else{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
config.php:
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'iphone');
DbConnect.php:
<?php
class DbConnect
{
private $conn;
function __construct()
{
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect()
{
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
DbOperation.php:
<?php
class DbOperation
{
private $conn;
function __construct()
{
require_once dirname(__FILE__) . '/Config.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createTeam($name, $memberCount)
{
$stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)");
$stmt->bind_param("si", $name, $memberCount);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return true;
} else {
return false;
}
}
}
However when I use HTTP POST method using Postman in Chrome, it states this
Notice: Undefined index: name in D:\xampp\htdocs\TestServ\api\createteam.php on line 9
Notice: Undefined index: member in D:\xampp\htdocs\TestServ\api\createteam.php on line 10
Warning: mysqli::__construct(): (HY000/1049): Unknown database 'iphone' in D:\xampp\htdocs\TestServ\includes\DbConnect.php on line 20
Failed to connect to MySQL: Unknown database 'iphone'
Warning: mysqli::prepare(): Couldn't fetch mysqli in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 20
Fatal error: Uncaught Error: Call to a member function bind_param() on null in D:\xampp\htdocs\TestServ\includes\DbOperation.php:21 Stack trace: #0 D:\xampp\htdocs\TestServ\api\createteam.php(18): DbOperation->createTeam(NULL, NULL) #1 {main} thrown in D:\xampp\htdocs\TestServ\includes\DbOperation.php on line 21
What does this mean, and what should I change?
Your first two errors are caused because of these two lines:
$teamName = $_POST['name'];
$memberCount = $_POST['member'];
The error (Undefined index) tells you that you have some non-existing variables, in this case name and member from your $_POST[] variable. Make sure your POST request is correctly made, see undefined variable for more information.
Your third error (Warning: mysqli::__construct(): (HY000/1049)) is caused because there isn't a database called iphone in your database system. Check if you have typed it correctly or if you haven't yet created an actual database with the name iphone.
The last error is caused because of the first two errors, since name and member aren't (correctly) defined in your POST request they have been set to NULL and the mysqli library doesn't like that.
Friends please help me out here
My Config File config.php
**<?php
define('DB_SERVER', 'localhost'); // Mysql hostname, usually localhost
define('DB_USERNAME', 'gani'); // Mysql username
define('DB_PASSWORD', 'gani'); // Mysql password
define('DB_DATABASE', 'gani'); // Mysql database name
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
My php file
**function instcount($updateid,$position)
{
include "config.php";
global $connection;
$sel=mysql_query("select * from register where regid='$updateid'");
$getcount=mysql_num_rows($sel);
$rowss=mysql_fetch_array($sel);
//print_r($rowss);
if($getcount==0)
{
$insert=mysql_query("insert into register (regid,dtentered) values ('$updateid',CURDATE())");
}
else
{
$update=mysql_query("update dailycount set net=100 where regid='$updateid'");
}
$selw=mysql_query("select sid,position from register where regid='$updateid'");
$rowd=mysql_fetch_array($selw);
if($rowd['sid']!='admin' && $rowd['sid']!="")
{
instcount($rowd['sid'],$rowd['position']);
}
//return 0;
mysql_close($connection);
}
$updated="10000";
$upfun=instcount($updated,$position);**
When i run above script I am getting below error
Warning: mysql_close(): 4 is not a valid MySQL-Link resource
Any one please help me out....
The problem is the
global $connection;
line of the code. You include the file within the function and according to php manual on include:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs.
This means, that the $connection variable becomes a local variable, since the include is within the function.
Either move the include out of the function or delete the global $connection; line from your code.
I am receiving the following error when loading my index page:
Fatal error: Call to a member function prepare() on a non-object in /Applications/MAMP/htdocs/parse/helloworld/helloworld/libraries/Database.php on line 32
I will place all of the relevant code below, sorry for the length but it should be fairly straight forward to read. The short version is I am practicing PDO and PHP classes so I am remaking an existing project I had on a different machine. (which is why a there is a lot of calls in the index file which acts more like a controller).
I am pulling my hair out here because it works on my other machine and from what i can tell the two projects are identical... I am just getting this error. I had this in my previous project, but that was because I had misspelled the database in the config file... I am 100% positive I did not do that again but I don't know what else I missed -- clearly the PDO class is not being made if I var_dump it returns null... Any and all help would be greatly appreciated (especially if it is in regards to my PDO class style I am just following a blog which seemed to make sense when it worked).
EDIT:
After some debugging it was clear that the try block in the database class was failing because a connection could not be established. This was clear after running $this->error = $e->getMessage() which returned:
string(119) "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)"
As the accepted answer below states the error indicates localhost trying to connect via a unix socket and mysqld not being able to able to accept unix socket connections.
So the original error leads to the ultimate question of: how do you connect to a unix socket when mysqld is not accepting unix socket connections and/or why does mysqld not accept unix socket connections?
End EDIT.
This is my (relevant) PDO class:
<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
} // Catch any errors
catch ( PDOException $e ) {
var_dump($dsn);
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
This is the index file that gets called
<?php
require('core/init.php');
//Create objects...
$type = new Type;
$post = new Post;
$group = new Group;
$follower = new Follower;
//Create template object
$template = new Template('templates/front.php');
$template->types = $type->getAllTypes();
$template->groups = $group->getAllGroups();
$template->posts = $post->getAllPosts();
$template->replies = $post->getReplies();
$template->followers = $follower->getAllFollowers();
echo $template;
and these are the other relevant files:
config --
<?php
//DB Params
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_NAME", "dobbletwo");
define("SITE_TITLE", "Welcome To Dooble!");
init --
//include configuration
require_once('config/config.php');
//helper functions
require_once('helpers/photo_helper.php');
require_once('helpers/system_helper.php');
//Autoload Classes
function __autoload($class_name){
require_once('libraries/'.$class_name . '.php');
}
for the sake of brevity (which may be far gone at this point I will only show one of the classes i load to prove that I am constructing the db(type, post, group, follower, template...)
<?php
class Type {
//Initialize DB variable
public $db;
/*
* Constructor
*/
public function __construct(){
$this->db = new Database;
}
the mysql libraries seem to interpret localhost as meaning you want to connect via a unix socket. your error indicates your mysqld isn't setup to accept unix socket connections.
to connect via tcp/ip instead, change define("DB_HOST", "localhost"); to define("DB_HOST", "127.0.0.1");
I just created an android app in which app is connected with MySql through PHP files.. I did according to this tutorial this
But I am able to connect when igave localhost address when i gave my server address it is not working .. The following is db_connect .. i didnt make any change
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root");
// db user
define('DB_PASSWORD', "");
// db password (mention your db password here)
define('DB_DATABASE', "androidhive");
// database name
define('DB_SERVER', "localhost"); // db server
?>
this is the link i uploaded my file...
Warning: mysql_connect() [function.mysql-connect]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/96/11645896/html/app/db_connect.php on line 28
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Warning: mysql_close(): no MySQL-Link resource supplied in /home/content/96/11645896/html/app/db_connect.php on line 42
but message came like this... what I have to do...
You need to give a server address of your own.. Instead of androidhive's and give the username and password of that particular server.. and edit the db_config.php file according to that.. then try to connect..
Check your db credentials and make sure mysqld is running. Try this /etc/init.d/mysql status or http://www.cyberciti.biz/faq/how-to-find-out-if-mysql-is-running-on-linux/ to know if MySQL is up.