How I call my mysqli in order page? - php

I have this in db.php page:
function db_connect(){ $link = new mysqli(localhost, user, pass, table); }
And this is in other page:
require_once("db.php");
function register($username, $email, $password){
global $link;
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
But it doesn't work when I call "register". How should I call the function "db_connect"?

You can do it like this (PDO connection):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
You can make it become a global variable if you want.
$GLOBALS['db'] = $db;
Note that this is pdo, an example of a PDO database operation for your case, note that this uses prepared statements and is therefor quite safe from sql injections, and is quite easy to use:
function register($username, $email, $password){
$query = "INSERT INTO user (username, password, email) VALUES (:username, :password, :email)"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':email' => $email
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($result)
{
return true;
}
return false
}
And you can call it like this:
$registerSuccess = register($username, $email, $password);

have db_connect() return the $link, or make $link global in db_connect()
function db_connect() {
return new mysqli(localhost, user, pass, table);
}
function register($username, $email, $password) {
$link = db_connect();
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}

Related

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

PHP pdo insert query not working

<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.

PDO lastInsertId() returns 0

I've been looking, at other questions asking the same, and can't figure out why my query won't act like it should.
My query:
$stmt = db()->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo db()->lastInsertId();
When I do this the lastInsertId(); keeps returning 0.
My db() function:
function db()
{
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
try {
$db = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
// exceptions handles here
}
return $db;
}
function db()
{
static $db;
$dsn = 'mysql:host=localhost;dbname=message_board';
$username = 'root';
$password = 'root';
if (!$db) {
$db = new PDO($dsn, $username, $password);
}
return $db;
}
You're creating a new db connection every line.
Try:
$db = db();
$stmt = $db->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo $db->lastInsertId();

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Insert sql statement in php Error: No database selected

So I'm attempting to make a registration form. I've made a php MySQL class which uses the constructor to make the connection with new MySQLi() for verifyLogin function and mysql_connect() for my addElement function.
The error is with my addElement function, the SQL statement writes out properly but it doesn't seem to connect to the database. I've checked that all the names are correct. Any ideas?
<?php
class MySQL {
private $connection;
private $conn;
private $databaseName;
function __construct($dbServer, $dbUser, $dbPassword, $dbName) {
$this->connection = new MySQLi($dbServer, $dbUser, $dbPassword, $dbName)
or die('PROBLEM CONNECTING TO DATABASE');
$this->conn = mysql_connect($dbServer, $dbUser, $dbPassword);
echo $this->conn;
$databaseName = $dbName;
}
function verifyLogin($table, $email, $password) {
$query = "SELECT *
FROM ?
WHERE email = ?
AND password = ?
LIMIT 1";
if($statement = $this->connection->prepare($query)) {
$statement->bind_param('sss', $table, $email, $password);
$statement->execute();
if($statement->fetch()) {
$statement->close();
return true;
}
else {
return false;
}
}
}
function addElement($table, $firstName, $lastName, $email, $mobile, $password,
$faculty, $campus) {
$query = "INSERT INTO $table (first_name, last_name, email, mobile, password, faculty, campus_location)
VALUES('$firstName', '$lastName','$email','$mobile',
'$password','$faculty','$campus');";
echo $query;
mysql_select_db($this->databaseName, $this->conn);
if(!mysql_query($query)) {
die('Error: ' . mysql_error());
}
mysql_close($this->connection);
}
}
?>
To select a database in MySQLi, you need to select it like so:
$db = new mysqli("localhost", "my_user", "my_password", "database_name");
or
$db = new mysqli("localhost", "my_user", "my_password");
$db->select_db('database_name');
as opposed to MySQL:
$db = mysql_connect('localhost', 'my_user', 'my_password');
$db_selected = mysql_select_db('database_name', $db);
MySQLi : http://www.php.net/manual/en/mysqli.select-db.php
MySQL : http://www.php.net/manual/en/function.mysql-select-db.php
You are mixing the mysql and the mysqli php drivers.
Since the mysql driver is deprecated I would suggest going with the mysqli.
PHP Documentation:
http://www.php.net/manual/en/book.mysqli.php
Good Overview to get you started:
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/

Categories