a link to server could not be established - php

i write this code in Database class ...
public function DeleteArticle($list)
{
$this->setdata("DELETE FROM Article WHERE Code IN (" . implode(',', $list) . ")");
}
private function connect()
{
mysql_connect('localhost' ,'#######' ,'########' );
mysql_select_db('allatala_db');
}
public function setdata($query)
{
$this->connect();
mysql_query($query);
mysql_close();
}
and call it in my adminpage.php
if(isset($_POST['delete1']))
{
$obj=new Database();
$obj->DeleteArticle($_POST['checkbox']);
}
so... in my localhost server work it properly but in the server i have this problem
a link to server could not be established
Help me plz

Your code has no error so there is some minor mistake.
Just make sure of following things.
1) Your server is running, Also try to open phpmyadmin in browser.
2) Open phpmyadmin and check your username and password under utilities.
3) User which you have created must have rights which is needed.
I think your problem would be solve after checking this things.

Related

Login script issue with database

I wrote a login script for a website that I am building using resources I have found online. When I ran my code on a local server it worked fine but now that I am actually running it online on a real server it doesn't work. I think I have narrowed down my error but with being new to PHP and not having prior experience with MySql I can't really fix my problem. This is the file for the login script:
//login file
<?php
class Login{
private $db_connection = null;
public function __construct(){
session_start();
$this->dologinWithPostData();
}
private function dologinWithPostData(){
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->db_connection()->connect_errno) {
// escape the POST stuff
$email = $_POST['email'];
// database query, getting all the info of the selected user (allows login via email address in the
// username field)
$sql = "SELECT email, password
FROM users
WHERE email = '" . $email ."'";
$result_of_login_check = $this->db_connection->query($sql);//This is 0
// if this user exists
if ($result_of_login_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_login_check->fetch_object();
// using PHP 5.5's password_verify() function to check if the provided password fits
// the hash of that user's password
if ($_POST['password'] == $result_row->password) {
// write user data into PHP SESSION (a file on your server)
$_SESSION['email'] = $result_row->email;
$_SESSION['user_login_status'] = 1;
} else {
$this->errors[] = "Wrong password. Try again.";
$_SESSION['user_login_status'] = 0;
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "Database connection problem.";
}
}
print_r($this->errors);
}
public function isUserLoggedIn()
{
if (isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] == 1) {
return true;
}
// default return
return false;
}
}
?>
I run it in another file that is essentially the following:
//Run file
require_once("dbconfig.php");
include_once("login.php");
$login = new Login();
if($login->isUserLoggedIn() == true){
//go to another page }
The variables used to access the database are instantiated in dbconfig.php and are correct. With this code I get an error that says the page is not working and is unable to handle the request. When I comment out the line
if (!$this->db_connection()->connect_errno) {
and the else statement following it, the output is "This user does not exist". So I think the error has something to do with $this->db_connection()->connect_errno). If you can find where I went wrong or have any advice on how to rewrite the script to make it better, it is greatly appreciated.
This is a database establishing error your live remote server database configuration is different.Please verify you dbconfig.php file make sure
database name, host , port , username , password are well defined with your live database
This is wrong:
if (!$this->db_connection()->connect_errno) {
db_connection is simply a variable containing your DB connection object. It is NOT a method.
You probably want
if (!$this->db_connection->connect_errno) {
^--note lack of ()
instead.
I think issue with this follwoing check. your result gets more than 1 records.
// if this user exists
if ($result_of_login_check->num_rows == 1) {
......
}else{
$this->errors[] = "This user does not exist.";
}
make sure your email address is unique in Data table, if it is not unique then your above statement will fail and show the text "This user does not exist." from else part

Page goes blank when working with database

I am working on a form for a friend. When a user submits the form their IP address is added into a database table. Every time a user then visits the form I run a check to see if their IP address is already in the table. If it is then they have already submitted the form.
I did this previously but decided to change how it works and now when I got to run any queries or connect to the database the whole page goes blank.
Here is my database class (class.Database.inc.php):
<?php
/**
* MySQLi database; only one connection is allowed.
*/
class Database {
private $_connection;
// Store the single instance.
private static $_instance;
/**
* Get an instance of the Database.
* #return Database
*/
public static function getInstance() {
if (!self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Constructor.
*/
public function __construct() {
$this->_connection = new mysqli('localhost', 'MHP_TICKET_ADMIN', 'fZx_142n', 'MHP_TICKET_SYS');
// Error handling.
if (mysqli_connect_error()) {
trigger_error('Failed to connect to MySQL: ' . mysqli_connect_error(), E_USER_ERROR);
}
}
?>
The code at the top of the form file (index.php):
<?php
require_once('class.Database.inc.php');
// Check database to see if the user has already submitted.
$user_ip = $_SERVER['REMOTE_ADDR'];
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql_query = "SELECT ip FROM ip_address WHERE ip = '$user_ip'";
$result = $mysqli->query($sql_query);
if ($row = $result->fetch_assoc()) {
die('You have already placed your submission.');
}
?>
EDIT
I entered the credentials in the wrong order, and it took me 2 hours to figure that out...
I know you've fixed this now (and I would comment, but I've not quite reached 50 yet) but for future reference this may help - an unexpected blank page in PHP most likely means an error is being thrown.
I make a habit of including error_reporting(-1) at the top of my script (in this case, your class.Database.inc.php file) so I see those errors immediately while developing and debugging. Switch this to error_reporting(0) when you go live of course to make sure errors are hidden from end users.

PHP MySQL Yii - database reading not writing

I have a working Yii app on my local lamp stack. Now when I put the app on a lamp server the app reads the db and runs, but the app isn't successfully writing to the db. I'm getting no errors logs. Any thoughts?
Here's how I'm updating the db:
public function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
$model=$this->loadModel($uid);
$this->redirect($model->URL."?".$model->Unique_ID);
}
public function loadModel($uid)
{
$model=People::model()->findByPk($uid);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save();
} else {
$this->render('notice');
}
return $model;
}
The weird thing is, even when the db doesn't update the Login_Count and Last_Logged the user still gets redirected to their url, so the sql must be valid because the notice page never loads. Any thoughts?
Update + Solution
The problem ended up being that the mysql server had autocommit set to false. To override this at the app level add the following line to the config/main.php db array:
'db'=>array(
...
'initSQLs'=>array('SET AUTOCOMMIT=1',),
...
);
Yii: using active record with autocommit off on mysql server
The rendering of notice page doesn't stop your redirect. It might be rendered, but you won't be able to see it because of redirect. Try to refactor your code.
You're validating your model twice and the validation probably might be skipped since there's no data coming from App user.
You don't check if People model actually found.
There is CWebUser::afterLogin method which you can override to do this kind of stuff (update login count and last login date)
Maybe this way (quick fix) will work:
function actionIndex()
{
if ($_GET["yep"] == "") {
pd_error("You are not logged in!");
}
list($uid, $domain) = preg_split("/#/",$_GET["yep"],2);
if (null === ($model=People::model()->findByPk($uid))
throw new CHttpException(404);
$model->Login_Count++;
$model->Last_Logged=date('Y-m-d H:i:s');
if ($model->save()) {
$this->redirect($model->URL."?".$model->Unique_ID);
} else {
// echo CHtml::errorSummary($model)
$this->render('notice');
}
}

How can I display an alert/ message in object-oriented PHP?

Currently I have used JavaScript to display an alert to notify that the execution was successful, merely for testing purposes. How can I do that in PHP object-oriented style?
I've tried:
public $msg='May the force be with you.';
$this->msg = new msg();
...but result was a white blank page. JavaScript piece I tried works well though. Below is the complete code:
<?php
class database {
public $mysql;
private $db_host='localhost';
private $db_username='admin';
private $db_password='password';
private $db_name='db';
function __construct() {
$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name) or die (mysql_error() ); {
echo
"<script type='text/javascript'>
alert ('The Force will be with you, always.');
</script>";
}
}
function __destruct() {
$this->mysql->close();
}
}
?>
PHP is server-side, which means it runs on a machine different from the user.
Javascript is client-side, which means it runs on the user's machine.
The server should have no control over anything on the user's machine.
Therefore, an alert box from PHP is not possible. :)
You've got to stick with Javascript, which only runs client-side. That, or echo plaintext out onto the document itself.
FYI, this relationship brings up other fun questions, like, "how can Javascript talk to the server" (answer:ajax) and "can a script talk to another computer" (answer: yes, but it's not supposed to).
Try this code:
<?php
class database {
public $mysql;
private $db_host='localhost';
private $db_username='admin';
private $db_password='correcthorsebatterystaple';
private $db_name='projekt';
function __construct() {
$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name) or die (mysql_error() );
}
function pri()
{
echo
"<script type='text/javascript'>
alert ('The Force will be with you, always.');
</script>";
}
function __destruct() {
$this->mysql->close();
}
}
$msg=new database();
$msg->pri();
?>
In PHP, you can do print_r() for any variable (or var_dump()) to see the contents of an object or array, etc.
Doing this will dump the contents directly on the page source (but not as a browser popup).

Cakephp - detect if unable to connect to database and recover gracefully

I have a few sites built with Cakephp. If any of these sites lose their connection to the database for whatever reason it does not handle it well. Basically it renders itself inside itself trying to display an error over and over until the browser crashes. The rendering itself inside itself is caused by the use of requestAction from elements.
What I want to know is how can I check if the database connection exists
I tried this in the app_controller before filter:
if(!ConnectionManager::getDataSource('default'))
{
die(); //this will be a message instead
}
but it does not seem to work.
Thanks
Use the following code:
<?php
$filePresent = true;
if (!file_exists(CONFIGS.'database.php')):
echo '<span class="notice-failure">Database configuration file is not present. Please contact admin#website</span>';
$filePresent = false;
endif;
if ($filePresent!=false):
uses('model' . DS . 'connection_manager');
$db = ConnectionManager::getInstance();
#$connected = $db->getDataSource('default');
if (!$connected->isConnected()):
echo '<p><span class="notice-failure">Not able to connect to the database. Please contact admin#website</span></p>';
endif;
endif;
?>
Here I'm printing messages (in those tags). You can replace the echo line with die().
(Cakephp 3.x)
Just follow the example given in PagesController's Home view:
Basically it is:
use Cake\Datasource\ConnectionManager;
try {
$connection = ConnectionManager::get('yourconnection');
$connected = $connection->connect();
} catch (Exception $connectionError) {
//Couldn't connect
}
//connected

Categories