sql database query issues - php

For the last week a have been stuck on one part of my website, the register script. I have got it to create new users in the database which is fine however it when someone enters a duplicate user name that I have issues with.
The database is set up to not allow duplicated so if you try you get a lovely error printed on the web page and although functional doesn't look great.,
what I have been trying to do and have looked at many many examples of how to do it but it never works for me. I Would love some help and please don't be a jerk and say there are answers/ it's a duplicate because I have tried. If you don't want to help then move on :).
here is the code:
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
UPDATE 1
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
}
catch (Exception $e)
{
echo "username taken";
}
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
tried the try catch as suggested but same issue the server error is displayed on screen i think its because it still executes and it doesnt "crash".
here is the error i get: (when i try to register as admin which already exists)
error
UPDATE 2
same result :(
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (Exception $e)
{
echo "username taken";
}
}
?>
UPDATE 2
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (PDOException $e)
{
echo "username taken";
}
}
?>
still does the same :(
UPDATE 3
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = $uname ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
these 2 errors:
enter image description here
pdo_connect code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'pass');
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
?>

Before insert you will need to run a select statement, select id or what ever from you users table that matches the username supplied on register, if the select statement return results then the username is taken otherwise run the insert.
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = ? ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
You will need to modify my code to match with your methods, because as it stand you have done your own sql functions.

found it!
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'Unhackable');
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo "too slow, username already taken";
//echo $errorMsg;
}
}
?>
commented out echoing the error message and echoing a customised message, i know its not great but it does the job.

Related

Activating a registered account using code (PHP + JS)

I'm currently working on a project and managed to get a working registration and login form. Upon registration, the user is emailed with a 5 character activation code and is asked to insert it on the user profile page in order to change the status from active:0 to active:1 and gains permission to the rest of the site.
For some reason the activation code just simply won't work :/
The following code is the PHP code written to activate the account, I am using PDO queries to connect to the database, but I tried using a mysqli query too but didn't seem to work.
<?php
session_start();
// Allow the config
define('__CONFIG__', true);
// Require the config
require_once "inc/config.php"; //possibly have to change the location
include_once "inc/classes/DB.php"; //possibly have to change location
include_once "inc/classes/Page.php";
include_once "inc/classes/User.php";
Page::ForceLogin();
//
//$email = filter_input(INPUT_POST['email'] );
//$username = Filter::String($_POST['username']);
//$skills = Filter::String($_POST['skills']);
//$email = filter_input(INPUT_POST['email'] );
//$username = filter_input(INPUT_POST['username'] );
$return=[];
$User = new User($_SESSION['user_id']);
$username = $User->username;
////Connection Variables
//$host = 'localhost';
//$user = 'root';
//$password = '';
//$db = 'mdb_';
////Creating mysql connection
//$conn = new mysqli($host,$user,$password,$db);
//$username = $User->username;
$activationCode = User::Find(INPUT_GET['activationCode']);
if(isset($_GET['activationCode'])) {
if(!empty($_GET['activationCode'])) {
$query = "SELECT * FROM users WHERE username='.$username.'";
$result = query($con, $query);
if(ocirowcount($result) > 0){
while($row = mysqli_fetch_array($result)){
if($_GET['activationCode'] == $row["activationCode"]){
$con->query ("UPDATE users SET active=1 AND credit=100 WHERE username = '.$username.'");
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//header("Refresh:0");
}
else{
$return['error'] = 'Code incorrect, please try again';
}
}
}
echo json_encode($return, JSON_PRETTY_PRINT);
}
}
//$activationCode = filter_input(INPUT_GET, "activationCode" );
//if(isset($_GET['activationCode'])) {
// if(!empty($_GET['activationCode'])) {
// $query = "SELECT * FROM users WHERE username='$username'";
// $result = mysqli_query($conn, $query);
// if(mysqli_num_rows($result) > 0){
// while($row = mysqli_fetch_array($result)){
// if($_GET['activationCode'] == $row["activationCode"]){
// $sql = $conn->query ("UPDATE users SET active=1 AND credit=100 WHERE username = '$username'");
// $return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
// //header("Refresh:0");
// }
// else{
// $return['error'] = 'Code incorrect, please try again';
// }
// }
// }
// echo json_encode($return, JSON_PRETTY_PRINT);
// }
//}
//$activationCode = filter_input(INPUT_POST, "activationCode" );
//
// if(isset($_POST['activationCode'])) {
// $activationCode = Filter::String( $_POST['activationCode'] );
//
//
//
//
//
// $query = "SELECT * FROM users WHERE username='$username'";
// $result = mysqli_query($con, $query);
// if(mysqli_num_rows($result) > 0){
//
// while($row = mysqli_fetch_array($result)){
//
// if($_POST['activationCode'] == $row["activationCode"]){
//
//
// $activateUser = $con->query ("UPDATE `users` SET `credit` = :100, `active` = :1, WHERE `user_id` = :$user_id");
// //$sql = $con->query ("UPDATE users SET active=1, credit=100 WHERE username = '$username'");
//
// $return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//
// header("Refresh:0");
// }
// else{
// $return['error'] = 'Code incorrect, please try again';
// }
//
// }
// }
//
// echo json_encode($return, JSON_PRETTY_PRINT);
//
//// }
// }
?>
The code below is the db class that creates the $con in PDO
class DB {
protected static $con;
private function __construct(){
try {
self::$con = new PDO( 'mysql:charset=latin1;host=host;port=****;dbname=mdb_', 'root', 'pass'); //change connection string
self::$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
self::$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
self::$con->setAttribute( PDO::ATTR_PERSISTENT, false );
self::$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo "Could not connect todatabase."; exit;
}
}
public static function getConnection() {
//If this instance has not been started, start it.
if (!self::$con) {
new DB();
}
//Return the writeable db connection
return self::$con;
}
There are several issues here, from mixing database API's to possible SQL injection, string concatenation issues and incorrect SQL syntax in your UPDATE query.
If you're using PDO for your database connection, you need to remove all references to the oci* (which are for Oracle databases) and mysqli* (which is a different API and not compatible with PDO) functions, and use the PDO equivalents.
I will also remove $username from the queries and use prepared statements instead. $username may be coming from your own database, but I can't see how it got in there. If you do not have a limit on which characters a username can contain, and the username is properly escaped when it is inserted into your database, then it may contain single (or double) quotes that can still cause trouble in this code. Bottom line: if it was originally user input, it should never be trusted.
// I missed this in the code in your question
$con = DB::getConnection();
if (isset($_GET['activationCode'])) {
if(!empty($_GET['activationCode'])) {
// Note the placeholder ":username" -- PDO will fill that with
// $username for you (see $stmt->execute() below) and take care
// of adding quotes around it
$query = "SELECT * FROM users WHERE username = :username";
try {
$stmt = $con->prepare($query);
$stmt->execute(array(':username' => $username));
if ($stmt->rowCount() > 0) {
foreach ($stmt as $row) {
if ($_GET['activationCode'] == $row["activationCode"]) {
// note the syntax: "SET active=1, credit=100"
$update = $con->prepare("UPDATE users SET active=1, credit=100 WHERE username = :username");
$update->execute(array(':username' => $username));
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
//header("Refresh:0");
} else {
$return['error'] = 'Code incorrect, please try again';
}
}
}
} catch (PDOException $error) {
$return['error'] = (string)$error;
}
echo json_encode($return, JSON_PRETTY_PRINT);
}
}
Note that this can be somewhat optimised by just attempting the UPDATE query. For the sake of convenience, I'll also assume you only want the activation code to be able to be used on inactive accounts, which you aren't currently checking:
$con = DB::getConnection();
if (isset($_GET['activationCode']) && !empty($_GET['activationCode'])) {
$query = "UPDATE users SET active = 1, credit = 100 WHERE username = :username AND activationCode = :code AND active = 0";
try {
$stmt = $con->prepare($query);
$stmt->execute(array(
':username' => $username,
':code' => $_GET['activationCode']
));
if ($stmt->rowCount() > 0) {
$return['error'] = 'Your account is now activated! You have earned 100 Time-banking credits.';
} else {
$return['error'] = 'Code incorrect or account is already active, please try again';
}
} catch (PDOException $error) {
$return['error'] = (string)$error;
}
echo json_encode($return, JSON_PRETTY_PRINT);
}

PDO statement fetchall not returning required result

I have read all other PDO topic in stackoverflow and tried all the stuff, but still its not working, i don't know whats wrong
on the Edit/Change Password page
I am using this code
ob_start();
session_start();
require_once './../account/config.php';
$id = $_SESSION['id'];
if (isset($_POST["submit"])) {
$opwd = mysql_real_escape_string($_POST['oldpwd']);
$npass = mysql_real_escape_string($_POST['newpwd']);
$anpass = mysql_real_escape_string($_POST['renewpwd']);
$sql = "SELECT COUNT(*) AS count from users where id = :id";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll();
here, $result[0]["password"] is not fetching the result from table users and column password
I even tried $result["password"] but not working,
in other pages same method is working very perfect but here its not fetching result
So, even user puts correct old password, its returning Current Password is Incorrect
if($result[0]["password"] !== $opwd) {
$msg = "Current Password is Incorrect";
}
elseif($npwd !== $rnpwd) {
$msg = "New Passwords did not match.";
}
elseif (($result[0]["password"] === $opwd) && $npwd === $rnpwd) {
$sql = "UPDATE `users` SET (`password`, `retype`) = (:npswd , :anpwd) WHERE `id` = :id";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":npswd", $npass);
$stmt->bindValue(":anpwd", $anpass);
$stmt->bindValue(":id", $id);
$stmt->execute();
$msg = "Your Password is changed successfully";
$msgType = "success";
}
else {
$msg = "Error Occured. Please Contact us if you have some issue.";
}
}
catch (Exception $ex) {
echo $ex->getMessage();
}
}
Please guide me what am i missing here

How can I fix this MySQL Code

How can I fix the following code?
function userExists($pdow, $login)
{
$userQuery = "SELECT * FROM login u WHERE login=:user;";
$stmt = $pdow->prepare($userQuery);
$stmt->execute(array(':user' => $login));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$login = 'user';
$exists = userExists($pdow, $login);
if('$login')
$user= var_dump((bool) 'Exists');
{
echo "Login exsists!";
}
I have two problems with my code.
First error:
Error with echoing 'login exsists!'. I see this echo all the time in browser.
Second error:
When I get echo 'login exsists!' my code still inserts data to database.
Simply:
$servername = '';
$dbname = '';
$username = '';
$password = '';
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
function user_exists($dbh, $Login) {
$Q = $dbh->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':Login', $Login);
$Q->execute();
return $Q->fetch(PDO::FETCH_ASSOC);
}
//Lets try:
$user = user_exists($dbh, 'email#example.com');
if ($user) {
echo 'User: ' . $user['login'] . ' was found in the database.';
} else {
echo 'The user was NOT found.';
}
if($login)
// this line doesnt make any sense!
// $user= var_dump((bool) 'Exists');
// so this is not a valid if clause
{
echo "Login exsists!";
}`
try {
$pdow = new PDO('mysql:host=localhost;dbname=log_cdr', 'root', 'slawek132');
$pdow -> query ('SET NAMES utf8');
$pdow -> query ('SET CHARACTER_SET utf8_unicode_ci');
$pdow->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlw = "INSERT INTO login (login, pass, pass_v, email, email_v)
VALUES ('".$_POST["login"]."','".$_POST["pass"]."','".$_POST["pass_v"]."','".$_POST["email"]."','".$_POST["email_v"]."')";
function user_exists($login) {
$Q = pdow()->prepare("SELECT * FROM login WHERE login = :Login");
$Q->bindParam(':login', $Login);
$Q->execute();
if ($Q->rowCount() != 0) {
//User exist:
return $Q->fetch(PDO::FETCH_ASSOC);
} else {
//User doesn't exist.
return false;
}
}

Gives out {"error":true,"error_msg":"User already existed with abc#gmail.com"} even though user doesn't exists

I have tried out a code for user registration..problem is it gives me {"error":true,"error_msg":"User already existed with abc#abc.com"} even though the user doesn't exists in database..plzz help me out of this..pardon me if am wrong some were..!
here gose my /DB_Function.php/code
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
/**
* Storing new user
* returns user details
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
return false;
}
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = $email LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n>0){
return true;
}else{
return;
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
}
}
?>
And here gose my /*register.php code */
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {
// receiving the post params
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
echo json_encode($response);
}
?>
You should return true or false depending upon whether the user has been found in the database or not, plus there's small syntax error in your isUserExisted() function. Your isUserExisted() function should be like this:
// your code
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
// your code
You have the wrong query Syntax, Use the following:
INSERT INTO users(fname, lname, email, password, mobile, created_at)
VALUES ($fname, $lname, $email, $hash, $mobile, NOW())
When we use a php variable in double qoute then the value of that variable appear, while in a single quote exact that variable name appear. For example:
$x = "hello";
echo "The value is $x"; // The value is hello
echo 'The value is $x'; // The value is $x
Now you can see where you can correct your code.
You need to add quotes in your email and return false if email not found in your database. It is better to use bindParam and rowCount() to count number of rows return from your query
$sql = "SELECT email FROM users WHERE email = :email LIMIT :val ";
$dbh = $this->db->prepare($sql);
$dbh->bindParam(':email', $email, PDO::PARAM_STR);
$dbh->bindParam(':val', 1, PDO::PARAM_INT);
$dbh->execute();
$n = $dbh->rowCount();
if($n>0){
return TRUE;// return true here
}else{
return FALSE;// return false if not found in database
}

Data won't save into MySQL database

I can connect to my DB, but nothing saves into it. In the section where it is suppose to save it into the DB, it echos "New User" and the $sql line with the data that should be saved. Can anyone see why this shouldn't be saving my data?
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($dbh){
echo "Connected successfully";
}else{
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_SESSION['steamid'])) {
include ('steamauth/userInfo.php');
if (!empty($steamprofile['steamid'])) {
$stmt = $dbh->prepare("SELECT count(*) from user WHERE steam_id = :steam_id");
$stmt->bindValue(':steam_id', $steamprofile['steamid']);
$stmt->execute();
$count = $stmt->fetchColumn();
}
//Row will return false if there was no value
if ($count == 0) {
//insert new data
echo "New user";
$sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
echo($sql);
// die();
} else {
//User exist
echo "User exists";
}
}else{
echo "no user signed in";
}
Table Schema: http://gyazo.com/ef9badc3ae72b73557ed80efe2413ea3
There it goes.
if ($count == 0) {
echo "New user";
$sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
$dbh->query($sql); // You missed that line of code.
echo($sql); // This will only echo out your query, not the result.
} else {
//User exist
echo "User exists";
}
You didn't execute the INSERT sql statement. You can use the following statement after $sql:
$result = mysqli_query($sql);
Make sure you read the $result and do appropriate things, e.g.:
if($result === true) {
// success
} else {
// failed
}
As in your codes the $sql has not been executed, it will print only the variable. Execute it first.
Execute insert query. Try this snippet in your code.
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch (PDOException $ex) {
}

Categories