how to use php variables make query for sqlite3 [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('wifin.db');
}
}
$db = new MyDB();
$mac = 'test';
$ssid = $_POST['ssid'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ($mac,$ssid,$lat,$lon)");
$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
var_dump($result->fetchArray());
?>
i'm not sure how to use variables in php5, $mac should be a string, when i directly use mac=$mac, it return me bool(false), which means can't find, but when i use mac='test', it gives me result.

Never ever use string concatenation or replacement to put values into SQL statements; this will give you formatting problems (as you've seen) and allow SQL injection attacks.
Instead, use parameters:
$stmt = $db->prepare('INSERT INTO wifinTb(mac,ssid,lat,lon) VALUES (?,?,?,?)');
$stmt->bindValue(1, 'test');
$stmt->bindValue(2, $_POST['ssid']);
$stmt->bindValue(3, $_POST['lat']);
$stmt->bindValue(4, $_POST['lon']);
$stmt->execute();
$stmt = $db->prepare('SELECT * FROM wifinTb WHERE mac = :mac');
$stmt->bindValue(':mac', $mac);
$result = $stmt->execute();

What you initialize $mac with 'test', is what you are doing is assigning a string (PHP recognizes anything inside '' or "" as a string) to $mac. The value of this string is test. So you still need to surround the value in the query with '':
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ('$mac','$ssid','$lat','$lon')");

$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
Is currently being seen as one long string. You could get around this quickly by changing it to:
$result = $db->query("SELECT * FROM wifinTb WHERE mac='" . $mac . "'");
However, you'd be better reading up on PDO or mysqli bind functions rather than injecting like that.
Hope that helps?

Related

Propper conversion of PHP and SQL data types [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 1 year ago.
Improve this question
A seemingly minor problem are bothering me, something that should have a simple solution. I am currently running a server and a database, the database which contains data that I want to use in a PHP request on a website. I have created a function in PHP that does the following:
function getUserID($val){
include("config.php");
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$sql = "SELECT userid FROM users WHERE username=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $val);
$stmt->execute();
$result = $stmt->get_result();
if(getUserExist($val)){
$rowdata = mysqli_fetch_assoc($result);
$conn->close();
return $rowdata['userid'];
}
}
This works just fine.. HOWEVER. The returned data type, which is supposed to be an Integer ( 1, 2, 3, 4... etc. ), returns a value similar to an JSON object or int(1), depending on how I write it.
array(1) { ["userid"]=> int(4) }
I have tried:
$rowdata['userid']
$rowdata
How do I make the function return purely the integer value? When it is added to the database with following code-snippet:
...
$stmt = $conn->prepare("INSERT INTO users (user1, user2, user3) VALUES (?, ?, ?)");
$stmt->bind_param("isi", $user1, $user2, $user3);
$user1 = $_POST[getUserID($username)];
$user2 = $_POST['val2'];
$user3 = $_POST['val3'];
$stmt->execute();
$stmt->close();
}
$conn->close();
As mentioned, it retrieves data just fine, it is just the value that acts in an odd way. When this code is executed, $user1 or rather the final value within database has the value of NULL. (database accepts only integers in that slot).
It looks to me as if the problem does not lie in getUserID(), but in this line:
$user1 = $_POST[getUserID($username)];
What you're doing here is not setting $user1 to the value of getUserID() - instead, you're setting it to "the element in the $_POST array which has a key of whatever getUserID() returns". And there are very few scenarios where that makes sense.
I'm assuming the line you want to replace it with is
$user1 = getUserID($username);

Converting query to parametrised query [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a query on my site and have recently been hacked because of it.
I have spent a good 2 hours looking how to convert this query so it is secure and have not got anywhere.
If anyone don't mind, could you please convert this one for me just so I can see what to do on the rest?
$camera_id = $_GET['camera_id'];
$cameras = mysqli_query($conn, "SELECT * FROM cameras WHERE id = $camera_id");
$camera = mysqli_fetch_array($cameras);
Try something like this.
$camera_id = $_GET['camera_id'];
$cameras = mysqli_prepare($conn, "SELECT * FROM cameras WHERE id = ?");
mysqli_stmt_bind_param($cameras, $camera_id);
$cameras->execute();
While you are making the switch, switch straight away to PDO. It's far better than mysqli
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM cameras WHERE id = :camera_id");
$stmt->execute(array(":camera_id"=>$camera_id));
$result = $stmt->fetchAll();
or instead of fetchAll()
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
As you can see this is more readable. And if you later decide eto switch to postgresql the change is real easy.
This is using PDO and assumes that the camera id is a number (if it can contain non-numerical values swap the PARAM_INT for a PARAM_STR. The basic premise is that you separate the query from the variables and you bind the value of the desired item to a variable. Also note that you would need to alter the variables in the new PDO declaration to suit your own database. Note also that fetchAll() provides an associative array of the returned results - there are a number of other fetch() methods possible to give different outcomes - look for the official documentation.
$camera_id = $_GET['camera_id'];
$conn = new PDO('mysql:host=localhost;dbname=db', 'username', 'password');
$sql = "SELECT * from cameras where id = :cameraId";
$q = $conn->prepare($sql);
$q -> bindValue(":cameraId" , $camera_id, PDO::PARAM_INT);
$q->execute();
$cameraRows = $q->fetchAll();
foreach($cameraRows as $cameraRow){
$CID= $cameraRow["camera_id"];
//.... rest of the code
}

Use WHERE IN with PDO PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to build a shopping cart using PHP, I get a list of IDs from the products added to the basket, I then want to query my database with these IDS using a WHERE IN SQL statement to get the details of the items added to the basket.
At the moment my query just comes back with false.
if(isset($_SESSION["cart"])) {
foreach ($_SESSION["cart"] as $id => $value) {
$ids .= $id . ',';
$count += $value['quantity'];
}
$query = $database->find_item_db($ids);
EDIT I have now changed my function to use the PDO syntax.
function find_item_db($product_code) {
$query = substr($product_code, 0,-1);
$product_codes = explode(",", $query);
$product_code_new = "(".implode("', '", $product_codes).")";
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN :id";
$statement = $this->connection->prepare($sql);
$statement->bindParam(':id', $product_code_new);
$statement->execute();
return $done = $statement->fetchAll();
}
However this is still returning nothing, I get this error in my logs.
/var/www/html/sweetshop/partials/categories-nav.php(32): Database_Functions->find_item_db('1,10,6,23,')\n#2 /var/www/html/sweetshop/category.php(17): include('/var/www/html/s...')\n#3 {main}\n thrown in /var/www/html/sweetshop/classes/class-database-functions.php on line 139, referer: http://localhost/sweetshop/category.php?type=Chocolate
I know my connection works fine as all my other queries work perfectly.
1. Incorrect syntax
If $ids is something like:
$ids = "1,2,3,4,5";
Then the query is:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN (1,2,3,4,5)
Which is incorrect because each value needs to be wrapped in single quotes:
function find_item_db($product_code){
$query = substr($product_code, 0,-1);
//Wrap each product id
$product_codes = explode("," $product_code);
$product_codes = "'".implode("', '", $product_codes)."'";
//.......
}
That way the query will read:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN ('1', '2', '3', '4', '5')`
2. Mixing SQL APIs
mysqli_* syntax and PDO syntax are not interchangeable. bind_param() is for PDO, however your query is using mysqli.
When you are using $statement->bind_param(':id', $new);, what are you binding? There is no :id value in the query, and therefore the line is unnecessary as well as incorrect SQL query format!

Wordpress prepared LIKE query [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to use a prepared LIKE query within Wordpress, but it doesn't seem to be working. I've followed the codex for the syntax.
public function userByJobId($id){
global $wpdb;
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE = d%;", '%' . $wpdb->esc_like((int)$id)) . '%');
if(!empty($result)){
return $result;
}
return false;
}
Calling the method like so:
$userid = 1
$user = new Users();
$user_id = $user->userByJobId($userid);
Cant see where the issue lies..
A few points have been made already:
Syntax for prepare() is the same as that for sprintf; a decimal placeholder is %d, not d%
The LIKE keyword shouldn't be followed by an equals, just the expression to test against
A few other things:
You concatenate the LIKE % wildcard after the closing parenthesis for prepare(), where it should be concatenated before
get_row() will return an object by default, not just the ID, which is a property of the object returned
public function userByJobId($id){
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}users WHERE {$wpdb->prefix}job_id LIKE %d;",
'%' . $wpdb->esc_like((int)$id) . '%'
)
);
if($result){
return $result->ID;
}
return false;
}
The wordpress class reference tells me that:
Possible format values: %s as string; %d as integer (whole number);
and %f as float.
When you want to prepare a query with a like comparison you should double escape percentages.
So change
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE = d%;", '%' . $wpdb->esc_like((int)$id)) . '%');
To
$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM use_users WHERE use_job_id LIKE %%%d%%;",(int)$id));
You also don't have to escape values (the prepare method does that for you).
Warning: Non tested code

Output value from array (php, mysql) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
How do I get the value of id field?
$data = getById(1);
echo $data[0] or echo $data['id'] doesn't work.
Your function returns an array of arrays, so to get the first ID:
$data = getById(1);
echo $data[0]['id'];
Side notes:
Globals are undesirable. Consider passing the database connection object to the function as an argument instead.
Escaping like that is a primitive way of preventing SQL Injection. The use of a Prepared Statement would be more secure and easier.
or die(....) is bad practice because it exposes the detailed MySQL error to users, and it's hard to remove if you have written that hundreds of times. An alternative is trigger_error() which silently writes to your error log.
You no need to use while and array. Get single row and you can get without using array:
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
return $result->fetch_array(MYSQLI_ASSOC);
}
$data = getById(1);
echo $data['id'];

Categories