<?php
class MyConnection {
protected $username = 'root';
protected $password = '';
protected $host = 'localhost';
protected $db_name = 'testdbewewewewe';
public function connection() {
try {
$this->dbh = new PDO("mysql:host=". $this->host . ";dbname=". $this->db_name, $this->username, $this->password);
} catch (PDOException $e) {$e->getMessage();}
}
}
?>
hi im new in PDO i hope someone can asnwer my curiousity on this one, i try to make a connection in mysql using php with PDO, but when i already make this code the browser doesn't show any error all is doing good, but when i tried to intentionally make the database name wrong the browser didn't show any error at all and i'm just curious if im i really doing it right?
Just because your error reporting is wrong.
You should not catch error exceptions to show them in the browser - PHP can already do it for you.
So, make your class this way
class MyConnection {
protected $username = 'root';
protected $password = '';
protected $host = 'localhost';
protected $db_name = 'testdbewewewewe';
public function connection() {
$this->dbh = new PDO("mysql:host=". $this->host . ";dbname=". $this->db_name, $this->username, $this->password);
}
}
Then tell PHP to show errors in the browser,
error_reporting(E_ALL);
ini_set('display_errors', 1);
$conn = new MyConnection();
$conn->connection();
And have your exception shown first class.
Related
I am creating an application where in a user can register and login in order to add a task and to achieve that, I try to make use of a query builder. However, I can't able to login the user using that. Here is the sample snippet of my code to which I am using query builder in Code Igniter:
public function login_user($username = null, $password = null){
if (is_null($username) || is_null($password) {
return false;
}else{
if (password_verify($password, $db_password)) {
$db_password = $result->row(6)->password;
$result = $this->db->where('username', $username)
where('password', $password)
->get('users');
if(!empty($result)){
return $result->row(0)->id;
}return false;
}
}
}
I got that to work after modifying some of the code itself. The reason I am not being able to login is the fact that I am fetching the database after the password verify and that will not work and it will not fetch the result of the $db_password variable. Here is some of the modifications of my code which I got it to work:
public function login_user($username = null, $password = null){
if(is_null($username) || is_null($password)){
return false;
}else{
$this->db->where('username', $username);
$result = $this->db->get('users');
$db_password = $result->row(6)->password;
if(!empty($result)){
//Decrypt password from database when the user logs in
if (password_verify($password, $db_password)) {
return $result->row(0)->id;
}return false;
}return false;
}
I am new on pdo and classes. I use this code to connect to database if i write the database information manually. But i want to read all these information from text file which has 4 lines. I use this code below but something is wrong.
$sqlsrv_txt = "evrak_tip.txt";
$satirlar = file($sqlsrv_txt);
$host = substr($satirlar[0], strpos($satirlar[0], ":") + 1);
$db_name = substr($satirlar[1], strpos($satirlar[1], ":") + 1);
$username = substr($satirlar[2], strpos($satirlar[2], ":") + 1);
$password = substr($satirlar[3], strpos($satirlar[3], ":") + 1);
class Database
{
private $host = "HOST NAME";
private $db_name = "DB NAME";
private $username = "USER NAME";
private $password = "PASSWORD";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("sqlsrv:server=" . $this->host . ";Database="
.$this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING,
PDO::SQLSRV_ENCODING_UTF8);
}
catch(PDOException $e)
{
echo "Connection error: " . $e->getMessage();
}
return $this->conn;
}
}
As you can see in the code, i need to write host,db_name,username and password accoridng to variables coming from txt file.
Can anybody help me about this?
i fixed it by creating and reading ini file.
$config = parse_ini_file("config.ini");
$this->conn = new
PDO($config['type'].":server=".$config['host'].";Database=".$config['dbname'],
$config['user'], $config['password']);
I need to call stored procedure in my App Service. I'm following this tutorial to create a custom repository. But I could not find the Context.Database.
Here is the code:
[UnitOfWork]
public virtual async Task<List<string>> GetUserNames()
{
EnsureConnectionOpen();
using (var command = CreateCommand("GetUsernames", CommandType.storedProcedure))
{
using (var dataReader = await command.ExecuteReaderAsync())
{
var result = new List<string>();
while (dataReader.Read())
{
result.Add(dataReader["UserName"].ToString());
}
return result;
}
}
}
What is the Context.Database and how do I use it?
My application is MVC in .Net4.6.1.
Update 1
I have resolved this issue by inheriting MyApplicationRepositoryBase.
Now I face a new issue when trying to GetActiveTransaction. I don't have any idea about this. What can I do?
Here is the code:
private DbTransaction GetActiveTransaction()
{
return (DbTransaction)_transactionProvider.GetActiveTransaction(new ActiveTransactionProviderArgs
{
{"ContextType", typeof(MyDbContext) },
{"MultiTenancySide", MultiTenancySide }
});
}
Here is the error log:
System.NullReferenceException: Object reference not set to an instance of an object.
at Abp.EntityFramework.EfActiveTransactionProvider.GetActiveTransaction(ActiveTransactionProviderArgs args) in D:\Github\aspnetboilerplate\src\Abp.EntityFramework\EntityFramework\EfActiveTransactionProvider.cs:line 21
Update 2
I tried to comment out the command.Transaction and it worked:
private DbCommand CreateCommand(string commandText, CommandType commandType, params SqlParameter[] parameters)
{
var command = Context.Database.GetDbConnection().CreateCommand();
command.CommandText = commandText;
command.CommandType = commandType;
// command.Transaction = GetActiveTransaction();
foreach (var parameter in parameters)
{
command.Parameters.Add(parameter);
}
return command;
}
I still need to put my code under a Transaction, so I don't want to comment out this line. What should I do?
Now I faced the new issue when trying to get Active Transaction
Add this in PreInitialize method of YourProjectNameDataModule:
Configuration.ReplaceService<IEfTransactionStrategy, DbContextEfTransactionStrategy>(DependencyLifeStyle.Transient);
How can i check the availability of Redis connection in Laravel 5.4. I tried below code, but getting an exception with ping line. How can i do, if Redis is not connected than do something else to avoid exception?
No connection could be made because the target machine actively
refused it. [tcp://127.0.0.1:6379]
use Redis;
class SocketController extends Controller
{
public function sendMessage(){
$redis = Redis::connection();
if($redis->ping()){
print_r("expression");
}
else{
print_r("expression2");
}
}
}
Also tried this:
$redis = Redis::connection();
try{
$redis->ping();
} catch (Exception $e){
$e->getMessage();
}
But unable to catch exception
if you are using predis , then it will throw Predis\Connection\ConnectionException
Error while reading line from the server. [tcp://127.0.0.1:6379] <--when redis is not connected
so catch that Exception, you will get your redis is connected or not .
use Illuminate\Support\Facades\Redis;
public function redis_test(Request $request){
try{
$redis=Redis::connect('127.0.0.1',3306);
return response('redis working');
}catch(\Predis\Connection\ConnectionException $e){
return response('error connection redis');
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class ConnectionChecker
{
public static function isDatabaseReady($connection = null)
{
$isReady = true;
try {
DB::connection($connection)->getPdo();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
public static function isRedisReady($connection = null)
{
$isReady = true;
try {
$redis = Redis::connection($connection);
$redis->connect();
$redis->disconnect();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
}
I created a helper class to check redis and db connection
Make sure redis is installed
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
To test that your service is functioning correctly, connect to the Redis server with the command-line client:
redis-cli
In the prompt that follows, test connectivity by typing:
ping
You should see:
Output
PONG
Install Laravel dependencies
composer require predis/predis
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04
https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04
In your constructor you can check redis status connection like this:
/**
* RedisDirectGeoProximity constructor.
* #throws RedisConnectionException
*/
public function __construct()
{
try
{
$this->redisConnection = Redis::connection('default');
}
catch ( Exception $e )
{
throw new RedisConnectionException([
'message' => trans('messages.redis.fail'),
'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
]);
}
}
and in your exception :
namespace App\Exceptions\Redis;
/**
* Class RedisConnectionException
* #package App\Exceptions\Redis
*/
class RedisConnectionException extends \Exception
{
/**
* RedisConnectionException constructor.
* #param array $options
*/
public function __construct(array $options = [])
{
parent::__construct($options);
}
}
please try with catch (\Exception $e) incl. backslash
This is my database connection code when i'm not going to put it inside a function within the class it works but if its inside function it doesn't any idea?
class DBConnection {
private $connection;
function __construct(){
$this->open_connection();
}
public static function open_connection(){
try {
$connection = new PDO('mysql:host=localhost;dbname=practice','root','');
$connection->exec("SET NAMES 'utf8'");
$connection->exec("SET CHARACTER SET utf8");
$connection->exec("SET character_set_server=utf8");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
die($e->getMesage());
}
}
}// class ends
I think the problem in your code is you use a static function to return the connection and your constructor not assign to you private variable
first solution with private $connection :
class DBConnection {
private $connection;
function __construct(){
$this->connection = $this->open_connection();
}
public static function open_connection(){
try {
$connection = new PDO('mysql:host=localhost;dbname=practice','root','');
$connection->exec("SET NAMES 'utf8'");
$connection->exec("SET CHARACTER SET utf8");
$connection->exec("SET character_set_server=utf8");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
die($e->getMesage());
}
}
seconde with connection static
class DBConnection {
private static $connection = null;
function __construct(){
if (self::$connection == null)
$this->open_connection();
}
public static function open_connection(){
try {
self::$connection = new PDO('mysql:host=localhost;dbname=practice','root','');
self::$connection->exec("SET NAMES 'utf8'");
self::$connection->exec("SET CHARACTER SET utf8");
self::$connection->exec("SET character_set_server=utf8");
self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
die($e->getMesage());
}
}
I hope to help you.