I'm fiddling around on my test database, learning how to set it all up.
I'm using PHP and PDO objects to access my database and get Data from it.
I'm also using prepared statements against MySQL Injections.
This is the code I'm using:
mainframe();
function mainframe(){
$connection = establishConnectionToDatabase();
$result = getData($connection);
//var_dump($result);
//echo json_encode($result);
echo $result;
}
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
function establishConnectionToDatabase(){
try
{
$connection = new PDO('mysql:host=localhost;dbname=foundationtests',
'verwalter','test');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $connection;
}
The table Im Accessing looks like this (see screenshot):
https://imgur.com/I06RF9e
When executing the above code, I'm only getting back
Notice: Array to string conversion in D:\foundationtests\src\assets\php\test.php on line 12
Array
I already tried out without prepared statements and it worked. I don't know what I'm missing.
You query is fine, you can't echo an array.
As you're returning an array, try this
function getData($connection){
$fetch = $connection->prepare("SELECT * FROM users_tbl");
$fetch->execute();
$result = $fetch->fetchAll(PDO::FETCH_ASSOC);
return (object)$result;
}
This will return your value as an object. Then you can echo whatever value using $result->user_id for example.
You can learn more about objects here
UPDATE
As has been pointed out, you can also just make it return as an object by change the 4th line from $result = $fetch->fetchAll(PDO::FETCH_ASSOC); to $result = $fetch->fetchAll(PDO::FETCH_OBJ);, and then changing the last line back to return $result;
Related
I need to write a PHP function to echo out MySQL rows as I give it the SQL query I want to be executed as the function argument. I have tried out the following code but it is giving me an undefined index error
function runQuery($query) {
$conn = mysqli_connect('localhost', 'root', '', 'mydb');
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
the code I am using to call the function is;
runQuery(SELECT * FROM mytable WHERE id='5')
echo $resultset['name'];
this, however, gives me this error, undefined index 'resultset' on line 25. any kind assistance would be appreciated
You dont have a $resultset in the scope of where you call the function. The function creates one, but that is only visible inside the function.
You will also have to put QUOTES around the query, you are passing a string there so it needs to be quoted.
Your errors should have generated quite a few error messages, if you were not getting them I have added 4 lines of code you should add while testing code for example if you are testing on a LIVE server with error reporting turned off.
You should also change the function to ensure you always return something
So amend the call to
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
function runQuery($conn, $query) {
$resultset = [];
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
$resultset = runQuery($conn, "SELECT * FROM mytable WHERE id='5'");
// as result will now be a multidimentional array
// you will need to loop over that to get each returned row
foreach ( $resultset as $row ) {
echo $row['name'];
}
AFTER your edit there is another error
$conn is not created inside the function, so will be invisible in the function code unless passed as a parameter to the function (there is another way but lets not get into the bad habit of using global variables)
First, your code is probably vulnerable to SQL Injection. Please take care of that, by using prepared statements for instance.
https://www.w3schools.com/sql/sql_injection.asp
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
Other than that, you do not assign the return value of your function to a variable. You cannot use the $resultset defined in the function scope outside the function, as it is a different scope. Try the following:
$resultset = runQuery("SELECT * FROM mytable WHERE id='5'")
echo $resultset['name'];
I built a similar function recently - here is my code
function returnSQL($conn, $nameSql) {
$result = mysqli_query($conn, $nameSql);
if (!$result) {
return 0;
}
while ($res = mysqli_fetch_assoc($result)) {
$data[] = $res;
}
return $data;
}
The connection is setup outside the function and passed in as an argument along with the sql like this...
$conn = mysqli_connect($servername, $username, $password, $DBName);
if (!$conn) {
echo 'Failed to connect to database :- ' . $DBName . '<br>';
die();
}
$sql = "SELECT * FROM table";
$data = returnSQL($conn, $sql);
I'm no expert, but this works for me :)
What I notice from your code is that you are trying to access $resultset outside of the function it is declared in and I think it is not available as a global variable - perhaps it should be something like:
$returnValue = runQuery(SQL statement);
// $returnValue is assigned the array returned from runQuery()
echo $returnValue['name'];
Okay, I've never ever used dynamic functions, not sure why, I've never liked using explode(), implode(), etc.
but I've tried it out, and something went wrong.
public function fetch($table, array $criteria = null)
{
// The query base
$query = "SELECT * FROM $table";
// Start checking
if ($criteria) {
$query .= ' WHERE ' . implode(' AND ', array_map(function($column) {
return "$column = ?";
}, array_keys($criteria)));
}
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$fetch = $check->fetch(PDO::FETCH_ASSOC);
return $fetch;
}
This is my query.
Basically I will return the variable $fetch which holds the fetch method.
and then somewhere, where I want to use the while loop to fetch data, I will use that:
$r = new Database();
while ($row = $r->fetch("argonite_servers", array("server_map" => "Wilderness")))
{
echo $row['server_map'];
}
Now, I am not getting any errors, but the browser is loading and loading forever, and eventually will get stuck due to lack of memory.
That's because the loop is running and running without stopping.
Why is it doing this? How can I get this dynamic query to work?
EDIT:
$r = new Database();
$q = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo $row['server_map'];
}
One nice feature of PDO is that the PDOStatement implements the Traversable. This means you can iterate it directly:
// `$check` is a `PDOStatement` object
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$check->setFetchMode(PDO::FETCH_ASSOC);
return $check;
Use it:
$statement = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
foreach ($statement as $row) {
}
this is because you call your fetch function in a loop and it re-starts the query every time. You need to call the $check->fetch() in loop instead.
or in other words, if your fetch function (which should probably have a different name) would return $check, then on the returned object you should call fetch() in a loop:
$r = new Database();
$q = $r->fetch(...);
while($q->fetch()){...}
you also need to edit your fetch function to end like this:
$check->execute(array_values($criteria));
return $check;
}
I'm using PDO to grab records from a mysql table. The data will be encoded with json_encode() and printed through the Slim framework for the API:
$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
try {
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC); // THIS!!!
if($stmt->rowCount()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
} catch(PDOException $e) {
echo $e->getMessage();
}
});
Should I use
$data = $stmt->fetch(PDO::FETCH_ASSOC);
or
$data = $stmt->fetchObject();
? Any direct benefits on fetching the data as an object? I've read some examples but they never explain why. The only usage for the resulting data will be to print it in JSON format. Thanks!
It doesn't matter. Though I'd cut an object out with Occam's razor.
Also your code is slightly wrong and redundant. Here is a proper version
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
if ($data = $stmt->fetch()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
there is no point in setting fetch mode for the every query when you can set it globally.
numrows() call is also useless.
and of course catching an exception is redundant, insecure and unreliable.
I have a PHP function that I am converting from using the mysql extension to the mysqli extension.
Everything is going okay, until here. I previously used a mysql_result to get a single piece of data. There is no direct equivalent in mysqli, so I have tried the following but it still doesn't work.
function getdbvalue($table,$value,$idfield,$id) {
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
I have verified that the variables are passing to the function okay, and the function is actually getting triggered. If I return $id I see the ID numbers.
I don't get an error for the query.
SOLVED:
I needed to add the database connection variable as a global in the function:
Working code:
function getdbvalue($table,$value,$idfield,$id) {
global $dbh; // This was missing!
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
Thanks to everyone for their help. :)
Although it's good idea to automate simple selects, the implementation is highly insecure, and should never be used.
Make it accept SQL query and parameters. It will make it secure.
And also you have to use PDO instead of mysqli
function getdbvalue() {
global $pdo;
$args = func_get_args();
$sql = array_shift($args);
$stm = $pdo->prepare($sql);
$stm->execute($args);
return $stm->fetchColumn();
}
have to be used like this (you have to connect to PDO first):
$name = getdbvalue("SELECT name FROM users WHERE id=?", $is);
this is the only proper way
I've got the following function in a model, however it keep returning:
Message: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
And I for the life of me can't figure out why.
function getNames() {
$query1 = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
$dev = array();
while($row = mysql_fetch_array($query1))
{
$manu = $row['Manufacturer'];
$mod = $row['Model'];
$dev[] = $manu.' '.$mod;
}
return $dev->result();
}
Can anyone help?
Answer for CodeIgniter is:
$query1 = $this->db->query("SELECT * FROM table");
foreach($query1->result_array() as $row)
{
$manu = $row['column1'];
$mod = $row['column2'];
echo $manu.' '.$mod;
}
return $query1->result();
The problem is you're mixing CodeIgniter database methods with built in PHP database methods. mysql_fetch_array expects a resource, not a CI query object.
Check out the docs on fetching results.
Sometimes, when you get a lot of data (lines) to process, you may want to use native php mysql functions like mysql_fetch_array to save memory (for best memory saving I prefer mysql_fetch_row). In this case you can use this :
try {
$query = $this->db->query("SOME QUERY");
while($row = mysql_fetch_row($query->result_id)) {
/* ... */
}
$query->free_result(); //we talked about memory saving right ;-)
} catch(Exception $e) {
/* ... */
}