Safe way to connect database with php using MySQLi [closed] - php

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
I just cut down my long code to small so its easy to understand. I am building php based website. I am using MySQLi as i know some MySQL. And for me PDO is hard to learn in small time period.
I created three files
- db.con.php
- index.php
- logout.php
I will post my all three files and i just want to know if its safe or there is any Vulnerability
And i thanks to all who see my question and appreciate answer alot.
db.con.php
<?php
//db.con.php
class DB {
protected $db_name = 'demo';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function connect() {
$DBerror = 'Database Error';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect($this->db_host, $this->db_user, $this->db_pass)) or die($DBerror);
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE $this->db_name")) or die($DBerror);
return true;
}
}
$db = new DB();
$db->connect();
//start session
session_start();
?>
index.php
<?php
require_once 'db.con.php';
$userID = $_GET['userID'];
$userID = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $userID);
$CheckQuery = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM users WHERE id='$userID'");
$VerifyID = mysqli_num_rows($CheckQuery);
if ($VerifyID !== 1){
header("Location: logout.php");
}
while ($row = mysqli_fetch_assoc($CheckQuery)) {
$id = $row['id'];
$name = $row['name'];
}
echo "My id is $id and my name is $name";
?>
And last logout.php
<?php
//logout.php
session_start();
session_destroy();
echo "Logout successful";
?>

Make it PDO not mysqli
Leave DB class alone for a while
Learn prepared statements
db.con.php
<?php
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, 'root', '', $opt);
session_start();
index.php
<?php
require_once 'db.con.php';
$stmt = $pdo->prepare("SELECT 1 FROM users WHERE id=?");
$stmt->execute(array($_GET['userID']));
$row = $stmt->fetch();
if(!$row) {
header("Location: logout.php");
exit;
}
$id = $row['id'];
$name = $row['name'];
echo "My id is $id and my name is $name";
Look it works better without homebrewed wrappers

Related

i want get data from table sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a table register with email and username colums.
> ex - username email
> test test#gmail.com
> new new#gmail.com
SELECT * FROM Register WHERE email='test#gmail.com'
I can get this colom ,but i cant select username.i want assign username to variable
I think you want something like this if you use MySQL :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username, email FROM MyTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "username: " . $row["username"]. " - email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In my opinion you're probably a beginner with web development with databases.
I recommend you w3chools. You can reed various examples in this site:
https://www.w3schools.com/php/php_mysql_select.asp
Your question is not clear, but if you are new with database I recommend you to start with PDO instead of mysqli.
<?php
//Db connection
function pdo_connect_mysql() {
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phpcrud';
try {
return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to database!');
}
}
// User Input
$username = 'john';
$email = 'john#gmail.com';
$sql = 'SELECT * FROM register WHERE username = ? email = ?';
$stmt = pdo_connect_mysql() ->prepare($sql);
$stmt->execute([$username, $email]);
$register = $stmt->fetchAll();
?>

Update / echo dont work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I don't understand why this doesn't work :
$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = <?php echo $row['userID']; ?>";
I work with PDO
What is wrong here? Need some help
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in()) {
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$servername = "test.de.mysql";
$username = "test";
$password = "test";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = <?php echo $row['userID']; ?>";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$sql = "UPDATE tbl_users SET balance = balance - 250 WHERE userID = " . intval($row['userID']);
Also i would mention you select all the userFields while you only need userID which is unnecessary mem waste.

PHP OOP MySQL connection [closed]

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();
?>

Trouble with simple hit counter in PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm cobbling together a very simple PHP script, but I can't get it to work. I'm connecting to the SQL database, but it's not retrieving the value I want. I just have a single entry in a single table in a single database. I want to retrieve that value, then add one to it.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
//------ DATABASE CONNECTION --------//
mysql_connect($dbhost,$dbuser,$dbpass)
or die ("Unable to connect to database");
mysql_select_db($dbname)
or die ("Unable to select database");
$test = "SELECT FIRST('count') FROM $dbtable";
?>
This button has been clicked <?php echo $test; ?> times.
EDIT: Found a solution with the aid of angelo
<?php
//parameters to set
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
$dbcolumn = 'count';
//end of list of parameters to set
$connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$connect){die("Connection error");}
$test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
$assoc = mysqli_fetch_assoc($test);
$num = $assoc[$dbcolumn];
?>
This button has been clicked <?php echo $num; ?> times.
<?php
$plus = $num+1;
//mysqli_query($connect,"INSERT INTO ".$dbtable."('".$dbcolumn."') VALUES ('".$plus."')");
mysqli_query($connect,"DELETE FROM counter WHERE count = $num");
mysqli_query($connect,"INSERT INTO counter (count) VALUES ($plus)");
?>
Why your code is not working
You're not launching your query
Warning
You're using mysql_ functions, which are deprecated. You should use mysqli_ instead.
Solution
Use this code:
<?php
//parameters to set
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
$dbcolumn = 'col';
//end of list of parameters to set
$connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$connect){die("Connection error");}
$test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
$assoc = mysqli_fetch_assoc($test);
$num = $assoc[$dbcolumn];
?>
This button has been clicked <?php echo $num; ?> times.
Please note that this code only shows the number of clicks.
To add one to this value, append the following code to the previous one:
<?php
$plus = $num+1;
$query = "UPDATE ".$dbtable." SET ".$dbcolumn."='".$plus."'";
mysqli_query($connect,$query);
?>

Can't connect on database on my localhost [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I have php script:
<?php
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$con = mysql_connect($host, $username, $pass);
if (!$con) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
running on remote server and when I execute it and try to connect to database located on my PC i get an error:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '109.60.110.255' (4) in /home/a6859995/public_html/zavrsni/connect.php on line 12
How can I fix that?
I recommend to use pdo like this:
class_config.php:
class class_config {
public static $db_host = 'localhost';
public static $db_name = 'yourdbname';
public static $db_user = 'youruser';
public static $db_pass = 'yourpass';
}
class_pdo.php:
require_once "class_config.php";
class class_pdo {
public static function dbFactory() {
$host = class_config::$db_host;
if(strpos($host,":") !==false) {
$parts = explode(":",$host);
$hostname = "unix_socket=".$parts[1];
} else {
$hostname = "host=$host";
}
$user = class_config::$db_user;
$pass = class_config::$db_pass;
$dbase = class_config::$db_name;
$pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
use it in your script like this:
require_once("class_pdo.php");
$pdo = class_pdo::dbFactory();
$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE id = :id ");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
[...]
Try This instead: mysql_connect() is deprecated so use mysqli_connect...
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$databae = $_GET['database'];
$con = mysqli_connect($host, $username, $pass, $database);
if (mysqli_connect_errno()) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
Though mysql_connect() is deprecated try using PDO.. I am just presenting it in mysql_connect for you..
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$database = $_GET['database'];
$connect=new connect($host,$username,$pass,$database);
class connect{
function __construct($host,$user,$password,$db_name){
mysql_connect($host,$user,$password) or die("Connection error");
mysql_select_db($db_name);
$error=mysql_error();
if (!empty($error))
{
echo $error;
}
}
}
Thanks everyone on help. Main problem were privileges on MySQL database, but PDO usage helped me to understand how it's to be done these days, sorry on n00b code at start :D

Categories