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

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.

Related

Using database class with PDO [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 7 years ago.
Improve this question
The classic first liner - have seen similar questions on SO but none that truly help me understand the crossroads I am at.
A little background before the code - I am not new to PHP or PDO (though not an expert either), but am a complete newbie to Object Oriented PHP and am trying to get the balance right of when to use classes and when it is possibly overkill.
The answer I'm hoping is in two parts. Firstly, it is good practice to create a wrapper database class when using PDO - for connection, basic queries etc.
Secondly, if not - are there better ways to speed up query writing?
EDIT Whilst I am questioning the code below, really I am question the PDO wrapper class approach overall - so the class below could be much larger than this, but is there any need/benefit?
See the following code;
NOTE: The class file is called via spl_autoload_register() in config.php
class_database.php
class Database
{
private $conn;
public function __construct() {
$this->openConnection();
}
public function openConnection() {
try {
$this->conn = new PDO('mysql:host=' . DB_SERVER . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'There was an error connecting to the database, Error: ' . $e->getMessage();
die();
}
}
public function getAll($sql, array $params) {
$stmt = $this->conn->prepare($sql);
$stmt->execute($params);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
generic_file.php
require_once '../includes/config.php';
$dbh = new Database();
$sql = ("SELECT * FROM users where id = :id and username = :username");
$id = 1;
$username = 'craig';
$params = array(':id' => $id,
':username' => $username);
$row = $dbh->getAll($sql, $params);
var_dump($row);
Now, to me this seems totally pointless. Using PDO alone, not a wrapper class, this query would be just as simple to write. On top of this - what if I want to use different fetch methods - I'd have to write more methods in the class.
Also, previously I have used a simple function to instantiate and return a new PDO object, simply including that file and assigning a variable to the function return was simple as quick - again I feel the class method is overkill.
Also, with my code above, and by doing this in a class, am I not losing the benefit of 'preparing' the statement as I will have to pass the sql statement in each time, even just to change the variables for the same statement?
However, I find lots of examples online, and especially on Lynda.com which I am using currently, of database wrapper classes. On top of this - I am no expert, and therefore what I feel is overkill may actually be best practice and strongly recommended, hence looking to you SO experts to help me out!
So...back to my question - is there a good reason to use such a class when using PDO?
If not, is there another DRY method that others use to minimize lines of codes needed for queries using PDO?
Thanks in advance.
I had your same question at one time.
The benefit to abstracting the database away is you can assure all connections are made correctly and if you ever do need to change the type of database there is only one spot that you need to change the code for. It also makes it easier to check the queries issued because you know if you echo and exit in the class all of the queries will able to be checked.
The way I solved it was by creating a class where the constructer established the connection and assigned it to a private variable while also setting the table in the database too.
The best way is to then have a few public functions to create, retrieve, update, and delete. Which is sometimes called CRUD.
For each function the only and first parameter is an array. For creating it takes the array and creates a prepared statement with it and then executes it.
It does a very similar thing with the others but for retrieve the array is what is being matched, for update it takes the things ending in id and sets the rest to update where the id = provided, and for delete it deletes where all of the keys = value in the table.
EDIT:
Here is the delete function I put in the class. If one of the parameter's values is an array it will prepare the statement and cycle through it. That is only for one variable changing though. You could also have it where you pass an array with the values of the numerical indexes being an array of what you would want to insert though that is not how I set up my code.
public function delete($info) {
$dbh = $this->dbh;
if (isset($info['submit_action'])) unset($info['submit_action']);
$where = array();
foreach (array_keys($info) as $name) {
$where[] .= "$name = :$name";
}
//echo "DELETE FROM {$this->table_name} WHERE " . implode(" AND ", $where) . ";"; exit;
$data = $dbh->prepare("DELETE FROM {$this->table_name} WHERE " . implode(" AND ", $where) . ";");
foreach ($info as $name => $value) {
if ($array_value == $name) $data->bindParam(":$name", $array_info);
else $data->bindValue(":$name", trim($value));
}
foreach ($info as $name => $value) if (is_array($value)) { $array_value = $name; break; }
if (isset($array_value)) {
foreach ($info[$array_value] as $array_info) {
try {
$data->execute();
}
catch (PDOException $e) {
if (!is_null($this->error_msg))
handle_error($this->error_msg, $e->getMessage());
else
handle_error("There was a problem removing the {$this->subject}.", $e->getMessage());
}
}
} else {
try {
$data->execute();
}
catch (PDOException $e) {
handle_error(/*public error msg - could set this anyway you want*/, $e->getMessage());
}
}
// Send success msg
}

Printing PDO query results [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
I am trying to print all the results of a query, but for some reason I get the following error: Fatal error: Call to a member function fetch() on boolean in H:\Some-Location\ on line X
This is my code:
<?php
$query = "SELECT adID FROM given WHERE toUser = :userid";
$query_params = array( ':userid' => $_SESSION['user']['ID'] );
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
echo "Failed to run query: " . $ex->getMessage();
}
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
?>
What's wrong?
As the docs and the error show, execute returns a boolean: http://php.net/manual/en/pdostatement.execute.php
You need to call fetch() on the statement, not the return value of execute. : http://php.net/manual/en/pdostatement.fetch.php
so replace $result>fetch() with $stmt->fetch().
The execute() method on the PDOStatement does not return the results, it only signals if the query succeeded or not (only useful when not using exceptions).
PHP Documentation:
public bool PDOStatement::execute ([ array $input_parameters ] )
What you want to do is use the PDOStatement itself to get the data:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
Note: According to your current logic, the loop will execute even when an exception is thrown. Try either returning from the catch block or putting the loop inside the try block.
$result is only a boolean holding success/failure of execute statement.
You need to run fetch on $stmt:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
As per documentation here:
http://php.net/manual/en/pdostatement.fetch.php

Having issue using shuffle with array and mysql query [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' am running into a problem where an array is not being able to shuffle. I want the array to randomized for each page loads. I followed the documentation but something still wrong over here
Error Message
Warning: Invalid argument supplied for foreach() in E:\xampp\htdocs\projects\snppets\sidebar.php on line 65
This is the code that gets the friends list, makes the sting into array, counts the array and shuffles it.
$friends = get_friends_IDS($profile_id);
$friends = make_string_to_ARRAY($friends);
$friends_count = count($friends);
$friends = shuffle($friends);
This is the code that is in line 65
<?php
foreach($friends as $id){
$sql = "SELECT profile_id, profile_photo, profile_username, profile_name FROM profile WHERE profile_id='$id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
if($db->NUM_ROWS() > 0){
foreach($rows as $row){
$friends_profile_id = $row->profile_id;
$friends_profile_photo = $row->profile_photo;
$friends_profile_username = $row->profile_username;
$friends_profile_name = $row->profile_name;
}
}
}
?>
This function gets the friends list from the database
function get_friends_IDS($profile_id){
global $db;
$sql = "SELECT profile_id, profile_friends FROM profile WHERE profile_id='$profile_id' LIMIT 1";
$query = $db->SELECT($sql);
if($db->NUM_ROWS()){
foreach($db->FETCH_OBJECT() as $row){
return $row->profile_friends;
}
}
}
This is the function makes a string into array
function make_string_to_ARRAY($array){
$array = explode(',', $array);
return $array;
}
When I remove the shuffle then it works fine...
shuffle() returns boolean value.
So $friends = shuffle($friends); makes $friends as a boolean variable.
just use shuffle($friends); to shuffle it

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'];

query function breaks mysteriously [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 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);

Categories