Bind variables in PHP-MySQL - php

I am using below code to execute MySQL query in PHP.
$cus_id = '1';
$query = new QUERY();
$clause = "SELECT * FROM customers WHERE cus_id=:cus_id AND status='ACTIVE'";
$params = array('cus_id'=>$cus_id);
$result = $query->run($clause, $params)->fetchAll();
Now the question is: is it secure enough. Or do I need to bind the static String as well? Something like:
$clause = "SELECT * FROM customers WHERE cus_id=:cus_id AND status=:status";
$params = array('cus_id'=>$cus_id, 'status'=>'ACTIVE');

It's secure because ACTIVE isn't user input. So you don't need to bind it.

It's fine the way you have it. The value for status isn't being dynamically assembled and doesn't create any vulnerabilities.

Related

select sql row using pdo with where statement

This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.

Call SQL FUNCTION with parameters in PHP

I have a question. I would call a SQL function through PHP language.
EX. "SELECT * FROM dbo.openday_detail(eventID)"
I was trying this:
$eventID= 10000;
$params="#eventID int";
$paramslist="#eventID='$eventID'";
$sql = "SELECT * FROM dbo.openday_detail(eventID = #eventID)";
$dbsql = "EXEC sp_executesql
N'$sql',
N'$params',
$paramslist";
$result=mssql_query($dbsql,$link);
But it doesn't work.
Thanks!
You cannot pas an assignment inside the call to the procedure... try removing eventID = and be sure your #eventID is correctly initialized
I tried to insert directly the INT value, but it doesn't work...
I guess that the problem is the Table-Function...andI can't to access to DB to see/modify the function .
a workaround?
I think the correct statement would be :
$sql = "SELECT * FROM dbo.openday_detail(#eventID)";
or
$sql = "SELECT * FROM dbo.openday_detail("+ $eventID+")";

How to solve Illegal string offset ['id'] in php?

I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.

Codeigniter this->db->query

Does $this-db->query() have mysql injection protection? I was wondering because I use this in instances and have not done anything to protect against sql injection.
The ActiveRecord style of querying with CodeIgniter escapes parameters, but not query().
You can use active record in this manner:
$someAge = 25;
$this->db->select('names, age');
$query = $this->db->get_where('people', array('age' => '>' . $someAge));
Read more about it here: https://www.codeigniter.com/userguide2/database/active_record.html
No, db->query() is not SQL Injection protected by default, you got few options.
Use Query Bindings
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
For more complex quires where you have to build the query as you go on, use compile_bind() to get chunk of SQL.
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$safe_sql = $this->db->compile_bind($sql, array(3, 'live', 'Rick'));
etc.
Or use escape $this->db->escape() on parameters
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
It's always best practise to use form validation first and include things like xss_clear, max_length etc either way in combination with one of the above.
you can use query bindings.
Example from CI 3 user guide:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));

RAW SQL Query with Zend Framework

Is there a way to execute a SQL String as a query in Zend Framework?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly withput parsing it and creating a Zend_Db_Table_Select object from it "by hand". Or if thats possible create a Zend_Db_Table_Select object from this string, to execute that object.
How can I do that? I didn't find a solution for this in the Zend doc.
If you're creating a Zend_DB object at the start you can create a query using that. Have a look at this entry in the manual : https://framework.zend.com/manual/1.12/en/zend.db.statement.html
$stmt = $db->query(
'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?',
array('goofy', 'FIXED')
);
Or
$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
You can use the same query in Zend format as
$select = db->select()->from(array('t' => 'testTable'))
->$where= $this->getAdapter()->quoteInto('myColumn = ?', $s);
$stmt = $select->query();
$result = $stmt->fetchAll();
Here is an example for ZF1:
$db =Zend_Db_Table_Abstract::getDefaultAdapter();
$sql = "select * from user"
$stmt = $db->query($sql);
$users = $stmt->fetchAll();

Categories