Cannot pass whitespace separated value to Query - mysql

My project with PHP and MySql stuck here ,
$searchfriend = "Jason";
$status = query("SELECT status FROM users.profile WHERE name = ?" , $searchfriend );
The above statement works quite well.
When I replace,
$searchfriend = "Jason R"
It's not working. What is the solution ?
I have created my own query function with PDO.
function query()
{
$sql = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
static $handle;
if (!isset($handle))
{
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
$statement = $handle->prepare($sql);
if ($statement === false)
{
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
$results = $statement->execute($parameters);
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}

Related

Connecting Application to Mysql Database CPanel, utf8_general_ci

I have software or an application on a MacBook called Nano Hotel Booking, I am trying to connect it to my CPanel server but I get the error Unknown collation: 'utf8_general_ci'. Everything else works besides the error for UTF8 I have checked the setting on the Data
`
<?php
$database_host = "localhost";
$database_user = "12345";
$database_password = "12345";
$database_name = "12345";
$db_access_token = "";
$return_format = (isset($_REQUEST['return_format'])) ? $_REQUEST['return_format'] : 'json';
$res = array('success' => true, 'errormsg' => '', 'data' => '');
try
{
$filename = (isset($_FILES['uploadedfile']['name'])) ? $_FILES['uploadedfile']['name'] : '';
if(trim($filename))
{
$upload_dir = 'data';
$ar = explode('___', basename($_FILES['uploadedfile']['name']));
if(sizeof($ar) != 3) throw new Exception('Bad file name '.basename($_FILES['uploadedfile']['name']));
if(!trim($ar[0]) || !trim($ar[1])) throw new Exception('Bad folder name');
if(!trim($ar[2])) throw new Exception('Bad file name '.$ar[2]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[0]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[1]);
if(!file_exists($upload_dir))
{
if(!#mkdir($upload_dir, 0777)) throw new Exception('Can not create folder '.$upload_dir);
}
$upload_dir .= '/'.trim($ar[2]);
if(file_exists($upload_dir)) #unlink($upload_dir);
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_dir))
throw new Exception('Can not upload file '.$upload_dir);
} else
{
$params = $_REQUEST;
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : '';
if(!$action) throw new Exception('Action not found.');
$enc_request = (isset($_REQUEST['enc_request'])) ? $_REQUEST['enc_request'] : '';
$params = #json_decode(trim(base64_decode($enc_request)));
if($params == false) throw new Exception('Request is not valid');
$params = (array)$params;
// Connect user
$s_key = '';
if(isset($params['db_access_token']))
{
$s_key = $params['db_access_token'];
}
if($s_key !== $db_access_token) throw new Exception('Bad user.');
$controller = new apiController($database_host, $database_user, $database_password, $database_name);
if($action === 'checkconnection') throw new Exception('ok');
if(method_exists($controller, $action) === false ) throw new Exception('Action is invalid.');
$controller->request = $params;
$res['data'] = $controller->$action();
}
} catch(Exception $e)
{
$res['success'] = 0;
$res['errormsg'] = $e->getMessage();
}
switch($return_format)
{
case 'json': print(json_encode($res)); exit; break;
case 'xml': print(arrayToXml($res)); exit; break;
}
class apiController
{
public $request = array();
protected $conn;
public function __construct($host = '', $user = '', $psw = '', $dbname = '')
{
#$this->conn = mysqli_connect($host, $user, $psw, $dbname);
if(!$this->conn) throw new Exception(mysqli_connect_errno().' '.mysqli_connect_error());
#mysqli_query($this->conn, "SET CHARACTER SET utf8_general_ci");
#mysqli_query($this->conn, "set names utf8");
#mysqli_query($this->conn, "SET collation_connection = utf8_general_ci");
}
public function select()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$arr = $this->selectOne($value);
$array[] = (sizeof($arr) > 0) ? $arr[0] : array();
}
} else
{
$array = $this->selectOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function selectOne($sql = '')
{
if(!trim($sql)) throw new Exception('Empty sql.');
$offset = (isset($this->request['offset'])) ? (int)$this->request['offset'] : 0;
$limit = (isset($this->request['limit'])) ? (int)$this->request['limit'] : 20;
if($limit) $sql .= ' LIMIT '.$offset.', '.$limit;
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
$rows = mysqli_num_rows($result);
if($rows <= 0)
{
mysqli_free_result($result);
mysqli_close($this->conn);
return array();
}
$array = array();
$fields = mysqli_num_fields($result);
while ($row = mysqli_fetch_row($result))
{
$onerow = array();
for ($i=0; $i < $fields; $i++) $onerow[] = $row[$i];
$array[] = $onerow;
}
mysqli_free_result($result);
return $array;
}
public function execute()
{
$sql = (isset($this->request['sql'])) ? $this->request['sql'] : '';
$array = array();
if(is_array($sql))
{
foreach($sql as $value)
{
$array = $this->executeOne($value);
}
} else
{
$array = $this->executeOne($sql);
}
if($this->conn) #mysqli_close($this->conn);
return $array;
}
public function executeOne($sql = '')
{
$lastid = '';
$result = null;
if(!trim($sql)) throw new Exception('Empty sql.');
$str = strtoupper($sql);
if((strpos($str, 'CREATE') !== false)
&& (strpos($str, 'TABLE') !== false)
)
{
$sql = str_ireplace ('AUTOINCREMENT' , 'AUTO_INCREMENT', $sql);
$sql = str_ireplace ('COLLATE NOCASE' , '', $sql);
}
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
&& (strpos($str, '(0,') !== false)
)
{
$result = mysqli_query($this->conn, 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
if(!$result) throw new Exception(mysqli_error($this->conn));
}
$result = mysqli_query($this->conn, $sql);
if(!$result) throw new Exception(mysqli_error($this->conn));
if((strpos($str, 'INSERT') !== false)
&& (strpos($str, 'INTO') !== false)
&& (strpos($str, 'VALUES') !== false)
)
{
$result = mysqli_query($this->conn, 'SELECT LAST_INSERT_ID()');
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_row($result))
{
$lastid = $row[0];
break;
}
}
}
$array = array();
$array[] = array($lastid);
if($result !== true) mysqli_free_result($result);
return $array;
}
public function getFieldFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
if(sizeof($arr[0]) == 0) return $def;
return $arr[0][0];
}
public function getFieldsFromSql($sql = '', $def = '')
{
if(!$sql) return $def;
$this->request['offset'] = 0;
$this->request['limit'] = 1;
$arr = $this->selectOne($sql);
if(sizeof($arr) == 0) return $def;
return $arr[0];
}
public function getArrayFromSql($sql = '')
{
if(!$sql) return array();
$this->request['offset'] = 0;
$this->request['limit'] = 100000;
return $this->selectOne($sql);
}
public function runScript()
{
$php = (isset($this->request['sql'])) ? trim($this->request['sql']) : '';
$nano = $this;
$php_res = #eval($php);
if($this->conn) #mysqli_close($this->conn);
if(is_array($php_res))
{
if(sizeof($php_res) > 0)
{
if(is_array($php_res[0])) return $php_res;
}
return array($php_res);
}
$array = array();
$array[] = array($php_res);
return $array;
}
}
?>
`
I have tried changing the UTF8 to almost everything else.

codeIgniter how can i create session into login controller

How can I create login session name? I tried but it didn't work for me.
Here is my code:
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
return true;
}
else {
return false ;
}
}
loginControler;
public function checkLogin(){
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if($this->form_validation->run() == false){
$this->load->view("login");
}
else {
redirect("SiteCont/index");
}
}
public function verifyUser(){
$name = $this->input->post("username");
$pass = $this->input->post("password");
$this->load->model("loginModel");
if($this->loginModel->login($name, $pass)){
return true;
}
else {
$this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
return false;
}
Only I need something ;
if($this->session->userdata('name')){
//show dashboard
}
else {
//show login
}
in the login page.
loginModel
public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
//set the session data (you can add more values to array according to your needs)
$data = array(
'user_id' => $ret->user_id, //change your actual user id field
);
$this->session->set_userdata($data);
//set the session data
return true;
}
else {
return false ;
}
}
To check
if($this->session->userdata('user_id')){
//redirect to dashboard
}
else{
//redirect to login
}
This will work properly. Change name of variables according to your needs.

Convert MySQL to pdo statement with json

I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>

PDO in Classes: Call to a member function prepare() on a non-object

I try to work with classes and PDO but I don't know how to fix the Problem.
With the help of var_dump($pdo) in RunQuery (after $pdo = self::$pdo_conn;) i get the value "null". Can anybody please help me how i can get the pdo object there? Or am I completely wrong with it?
index.php
require_once ('assets/socialbar/defines.php');
require_once ('assets/socialbar/mysql/classes/class.socialbar.php');
$ajaxid = 1;
$getinfo = "";
$getinfo = Socialbar::getInfo($ajaxid);
print_r($getinfo);
class.socialbar.php
require_once(MYSQL_DIR . 'config/pdo_connection.php');
class Socialbar extends Connection {
function __construct(){
parent::__construct();
}
public function GetInfo ($ajaxid) {
$sql = "SELECT * FROM uploads WHERE id = :ajaxid ";
$inputs = array('ajaxid' => $ajaxid);
//$stmt = $this->RunQuery($sql, $inputs);
$stmt = parent::RunQuery($sql, $inputs);
$rowCount = $stmt->rowCount();
if($rowCount > 0){
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
return $rowCount;
}
}
}
pdo_connection.php
abstract class Connection {
protected static $pdo_conn;
private $dsn, $user, $pass;
function __construct (){
require_once MYSQL_DIR . 'pdo_config.php';
$host = $config['db']['host'];
$dbname = $config['db']['dbname'];
$port = $config['db']['port'];
$this->user = $config['db']['user'];
$this->pass = $config['db']['pass'];
$this->dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname;
$this->Start();
}
protected function Start(){
try {
$this->pdo_conn = new PDO($this->dsn, $this->user, $this->pass);
} catch (PDOException $e){
print_r($e);
exit(0);
}
}
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
if(is_null($inputs)) {
$pdo->query($sql);
} else {
try {
$stmt = $pdo->prepare($sql);
if ($stmt) {
$stmt->execute($inputs);
} else {
print_r("Unable to prepare query");
}
} catch (PDOException $e) {
print_r($e);
exit(0);
}
}
return $stmt;
}
}
pdo_config.php
$config['db'] = array(
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'dbname' => 'images',
'port' => '3306',
);
IMHO problem is your understanding or misunderstanding of static variables and functions.
So if you declare:
abstract class Connection {
protected static $pdo_conn;
That means that you can access $pdo_conn even if you had not instatntiate the object of your class and did not pass the __construct so if you have not passed __construct what value holds that property? Correct - NULL ;-)
so when you try to:
function RunQuery ($sql, $inputs=null){
// $pdo = $this->pdo_conn;
$pdo = self::$pdo_conn;
What will you get? Correct $pdo = NULL. And commented line looks as correct one.
There is no reason to declare and call pdo_conn as static property.
It could be private, protected even public but not static.
Try to instantiate the object first:
$socialBarObj = new Socialbar();
$getinfo = $socialBarObj->getInfo($ajaxid);
print_r($getinfo);

How to I bind 'id' from mysql query to $_SESSION

I am trying to set the $_SESSION to the 'id' in the mysql query. How do I do that?
public function Login($email, $pass){
if(!empty($email) && !empty($pass)){
$st = $this->db->prepare("select email, pass, id from login where email=? and pass=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if ($st->rowCount() == 1){
//login correctly
$_SESSIONS['user_id'] = XXX;
header('Location: main.php');
} else{
echo "Wrong password";
}
} else {
echo "Please enter username and password";
}
}
Here's my answer:
public function Login($email, $pass){
if(!empty($email) && !empty($pass)){
$st = $this->db->prepare("select email, pass from login where email=? and pass=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if ($st->rowCount() == 1){
//login correctly
$_SESSIONS['user_id'] = $st->fetchALL();
header('Location: main.php');
} else{
echo "Wrong password";
}
} else {
echo "Please enter username and password";
}
}