query function breaks mysteriously [closed] - php

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 8 years ago.
Improve this question
I have a Database class which has multiple functions to execute queries. One of them is the simplest of them all:
public function query($query) {
return $this->_link->query($query);
}
$this->_link->query works in other cases, so it should work here. From a file that has an instance of a class, I do this:
function createLineChart() {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart();
but it breaks on the $result line. The query is also valid, I've testid it. Am I missing something?

Your problem is $db is out of scope of the createLineChart() function. You can either use the global method:
function createLineChart() {
global $db; // <-- make the db var become available
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
Or pass the $db object to the function as an argument:
function createLineChart($db) {
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}
createLineChart($db);
More info about Variable Scope on the Manual.

function createLineChart() {
var_dump($db);
// this should probably return 'undefined'
global $db;
// so globalize it!
$query = "select * from tags";
$result = $db->query($query);
// do something with result
}

If $db is a class variable, then you need to refer it as:
$result = $this->db->query($query);

Related

How to use where as function and select function in POV of SQL Injection [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
As I have to fetch data multiple times so I created select function and where function is it write way to way to use and also in point of view of SQL Injection , this way is not good ? Please guide
function where($column, $value) {
return "AND $column = :$column";
}
function fetchCategory($where, $data1) {
// Create a PDO instance
$db = Database::newInstance();
// Build the SELECT statement with a WHERE clause
$sql1 = "SELECT * FROM category WHERE 1=1 $where";
// Execute the SELECT statement with bound parameters
$row1 = $db->read($sql1, $data1);
// Return the result set
return $row1;
}
$where = where('cat_id', $value->parent_id);
$data1 = array(':cat_id' => $value->parent_id);
$result = fetchCategory($where, $data1);
if ($result) {
// Fetch the data from the result set
$data['Dis_05']= $result[0]->category;
} else {
// No data was found
echo "No data found";
}

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
}

strip_tags() on MySQLi Query and PHP Function [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 7 years ago.
Improve this question
I'm trying hard to learn how to create functions, and I don't know what I'm doing wrong here. Could someone explain it to me please?
I'm not using strip_tags(), why it's getting me this error?
I don't need it to return, I just to need to update database if
$xp is bigger than $row['basenumber']
Thank you!
$xp = $row['userxp'];
$lvl = $row['userlevel'];
contXP($xp, $lvl);
function:
function contXP ($xp, $lvl) {
$query = "SELECT
number, basenumber
FROM levels
WHERE number = '$lvl'";
$result = $conn ->query($query);
if (!$result) die ($conn->error);
$rows = $result->num_rows;
while ($row = $result->fetch_array (MYSQLI_ASSOC));
if ($xp >= $row['basenumber'])
{
// up level
$level = "UPDATE users
SET userlevel = userlevel + 1
WHERE idusers = '$iduser';";
$re_level = $conn ->query($level);
if (!$re_level) die ($conn->error);
$re_rows = $re_level->num_rows;
$re_row = $re_level->fetch_array (MYSQLI_ASSOC);
$re_level->close(); //close query
}
$result->close(); //close query
}
result:
Warning: strip_tags() expects parameter 1 to be string, array given in on line 32
strilp_tags() is definitely somewhere in your code to throw the error. Try posting all the codes involved so we can find out where your problem is coming from.

PHP MySQL query not working using my DB class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've set up a Database class, a User class and a UserTools class to interact with a MySQL database. It seems that my UPDATE, DELETE and INSERT commands are working find but I can't figure out what's going on with my SELECT statements. I'm only using mysql right not until I get everything working as I'd like, then I'll switch over to mysqli or PDO. But anyway, here's what I'm looking at....
DB class....
public function select($table, $where) {
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
return $this->processRowSet($result, true);
return $this->processRowSet($result);
}
public function processsRowSet($rowSet, $singleRow=false) {
$resultArray = array();
while ($row = mysql_fetch_assoc($rowSet)) {
array_push($resultArray, $row);
}
if ($single_row === true)
return $resultArray[0];
return $resultArray;
}
UserTools class
public function getUser($id) {
$db = new DB();
$result = $db->select('users', 'id = $id');
return new User($result);
}
There seems to be an issue with how I'm processing the rows or something. I've followed similar setups with UPDATE,DELETE,INSERT and they seem to work fine but I don't know whats going on here.
If I call an instance of new UserTools(), then try to run the getUser() function, it's not returning anything the way it's set up. If I keep the result from being pushed through the User class constructor, it just returns a Reference Value, meaning that I'm not processing the rows properly.
I have a feeling I'm overlooking something stupid here so any help would be greatly appreciated. Thanks!
For a start,
$result = $db->select('users', 'id = $id');
Should be
$result = $db->select('users', 'id = '.$id);
As Casimir mentioned, there's a typo in public function processsRowSet
I'd echo $sql; die; to check if the query is complete.
In UserTools class: 'id = $id' wouldn't parse in $id. Instead do "id = {$id}" or similar so that it can parse $id.

How can I use a database schema in PHP? [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 8 years ago.
Improve this question
I am writing a small PHP/MySQL application for personal use. This is my first time using PHP, so bear with me.
I wanted to be able to change the DB schema afterwards, if needed, so everything went into variables (stuff like table and column names). I used two approaches during development:
Global variables
db_schema.php:
$table = "table_name";
$column = "column_name";
main.php:
function do_db_stuff()
{
global $table;
global $column;
global $db;
$db->query("SELECT `$column_name` FROM `$table_name`;");
}
Defines
db_schema.php:
define (TABLE, "table_name");
define (COLUMN, "column_name");
main.php:
function do_db_stuff()
{
global $db;
$db->query("SELECT `" . COLUMN . "` FROM `" . TABLE . "`;");
}
Now, I like the nice syntax of the query string when I use variables - I do not need to use . concatentation, however this approach requires an unwieldy number of global statements at the beginning of each function. This was a dealbreaker. Approach number two does away with the globals, but the syntax is not so nice.
Is there a time-tried PHP-style solution to this problem?
What about this?
$schema = array(
'table' => 'spam',
'column' => 'eggs',
);
function do_db_stuff() {
global $db;
global $schema;
$sql = sprintf(
'SELECT `%s` FROM `%s`',
$schema['table'],
$schema['column']
);
$db->query( $sql );
}
I found the following solution which is pretty clean-looking:
db_schema.php
$table = "table";
$column = "column";
main.php
function do_stuff()
{
require "db_schema.php";
$db->query("SELECT `$column` FROM `$table`;");
}
I settled on the following solution which seems the most clean to me:
db_schema.php
$TABLE = "table";
$COL = "column";
main.php
function do_stuff
{
require 'db_schema.php';
$db->query("SELECT `$COL` FROM `$TABLE`;);
}

Categories