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'];
Related
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
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.
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
Okay, so excuse me if this is a silly question but I'm not all too familiar with MYSQL.
Here we go:
When you perform the following code:
$result = mysqli_query($this->con, "SELECT * FROM blogfeed WHERE id = 1");
$result = mysqli_fetch_array($result);
return $result;
it returns an array with all the information in the row where the id = 1.
Now, just for example let's say there is more than 1 row with the id of 1.
How would I make the query return an array with all of those rows?
Currently, it is only returning one of the rows and there are 2 of them.
$mres = mysqli_query($this->con, "SELECT * FROM blogfeed WHERE id = 1");
$results = array();
while($result = mysqli_fetch_array($mres)) {
$results[] = $result;
}
return $results;
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?
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
I used this code for displaying 4 numbers randomly without repeating, but i got error as resource id#3
$test = nonRepeat(0,4,4); //calling function nonrepeat defined earlier
for ( $i = 0; $i < 4; $i++ ) {
$result = mysql_query( "select * from abc where id='test[i]'" ); accessing data from data base as id in the array test.
print_r( $result );
}
1.- Don't use mysql_* functions they are deprecated and will not be included in future updates.
2.- Your question is pretty unclear, but when you execute a query using mysql_query you get a resource, so you need to iterate through this:
$test = nonRepeat(0,4,4); //calling function nonrepeat defined earlier
for($i=0;$i<4;$i++)
{
$result = mysql_query( "select * from abc where id='{$test[i]}'" ); <<<---- CHANGED
if ($result){
while ($row = mysql_fetch_assoc($result)) {
print_r($row); //Display each row data
}
}else{
print "Error:" . mysql_error();
}
}
Try this and see what is showing, and take a look to mysqli_ and PDO