Getting errormessage only if using function in MYSQL - php

I made a function to fetch a column and them render each row as a li.
But I am getting "Errormessage:" as result. I tried it without functon and that works fine.
Please help.
$nkFetch = function($link){
$table1Query = "SELECT * FROM table1";
$res = mysqli_query($link, $table1Query);
if (!mysqli_query($link, $table1Query)) {
printf("Errormessage: %s\n", mysqli_error($link));
}
$table1 = array();
while ($row = mysqli_fetch_array($res)){
$table1[] = $row;
}
shuffle($table1);
foreach( $table1 as $row ){
echo "<li>" . $row['WORD'] . "</li>";
}
}

Update
Given that you're using a lambda-style function (instance of Closure), and wish to use a globally available variable $link, you should write:
$nkFetch = function () use ($link)
{
//code here. $link is available
};
$nkFetch();
//or
$nkFetch = function ($link)
{
//code here
};
$nkFetch($link);//<-- pass mysqli here
Read the manual on anonymous functions
Very well, I'll bite.
You say this is a function. If so: are you passing the $con connection variable as an argument
Have you made sure the connection (mysql_connect call) was successful
As an asside: mysql_free_result really is a tad pointless if that's the last statement in your function. The resultset should be freed once all function variables go out of scope
Now, here's what your code should look like if you want to use that deprecated extension (BTW: try updating your PHP version, and set your error level to E_STRICT | E_ALL, you should see deprecated notices).
Assuming this is indeed a bona-fide function:
function getList($con)
{
if (!is_resource($con))
{//check if $con is a resource, if not... quit
echo '$con is not a resource!', PHP_EOL;
return;
}
$res = mysql_query('SELECT * FROM table1', $con);
if (!$res)
{//query failed
echo 'Query failed: ', mysql_error($con);
return;
}
while($row = mysql_fetch_assoc($res))
{//echo here already
echo '<li>', $row['WORD'], '</li>';
}
}
//call like so:
$dbConnection = mysql_connect('127.0.0.1', 'user', 'pass');//pass your params here, of course
if (!$dbConnection) exit(mysql_error());
getList($dbConnection);
A more modern way of writing this would be:
$db = new PDO('127.0.0.1', 'user', 'pass');
$res = $db->query('SELECT * FROM table1');
while($row = $res->fetch(PDO::FETCH_ASSOC))
{
echo '<li>', $row['WORD'], '</li>';
}
Check the PDO documentation

Related

how do i create a php function to echo out mysql data, a function that can be reused?

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

display all the rows retrieved by php from mysql db using function?

Class function that is retrieving values from db
public function retrieveFun()
{
include 'inc/main.php';//connecting to db.
$result = mysqli_query($con,"SELECT * FROM db order by name DESC");
while($row = mysqli_fetch_array($result))
{
$var = array('name' =>$row['name'] ,
'owner'=>$row['owner'],
'date'=>$row['date'] );
// echo $var["name"]."<br/>";
// echo $var["owner"]."<br/>";
// echo $var["date"]."<br/><br/>";
return array($var["name"],$var["owner"],$var["date"]);
}
}
and code where I want to display all the rows retrieved in desired format
$obj = new classname();
$id= $obj->retrieveFun();
echo //here i want to display all the rows retrieved in table format.
Please help me out as soon as possible
You've got return statement inside while loop, it has no sense. Try to put return statemanet outside the loop. To retrive result in table format i would do :
public function retrieveFun()
{
include 'inc/main.php';//connecting to db.
$result = mysqli_query($con,"SELECT * FROM db order by name DESC");
$resutlArray = array();
while($row = mysqli_fetch_array($result))
{
array_push($resultArray, $row);
}
return $resultArray;
}
Then to display your result in table format use :
$rows = $obj->retrieveFun();
echo '<table>';
foreach( $rows as $row )
{
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['owner'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '</tr>';
}
echo '</table>';
Put the return call outside your while loop. At the moment, only the first result would be stored before being returned. What you want to do is populate $var first before returning the variable.
When displaying the rows:
$rows = $obj->retrieveFun();
foreach( $rows as $key => $row ) {
echo $row[$key]['name'];
echo $row[$key]['owner'];
echo $row[$key]['date'];
}
See modification for $key support.
EDIT:
Also, when fetching the results, store them in an array.
$var = array();
while ( $row = mysqli_fetch_array( $result ) ) {
$var[] = array( ... );
}
http://www.w3schools.com/Php/php_mysql_select.asp
W3C is an amazing site for beginners. That page I linked has exactly what you need. It has examples and the source code all there to see, plus explanations. Read the examples and it'll explain it and you should be able to understand it.
If not, feel free to message me and I'll do what I can.
W3C has many tutorials that can cover just about all aspects of web, browse and be amazed!
It's good to check around the web before posting questions. We're here to help, but only if you try to help yourself first.
Hope it helps.
If you got your answer from this, please vote it up and mark it as the answer so others can find it easier.
Note: It's in the second section under 'Display the Result in an HTML Table'.
I really like the PDO approach over MySQLi it's much cleaner. Here's what I would do. A class with the DB connection and a public function inside the class.
Class + Function
class Database
{
private $db = null;
public function __construct()
{
$this->db = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'password');
}
public function retrieveFun()
{
$query = $this->db->prepare("SELECT * FROM db ORDER BY name DESC");
$query->execute();
return $query->fetchAll();
}
}
Then to retrieve data I use foreach
if (retrieveFun()) { //Verify if the DB returned any row
foreach (retrieveFun() as $key => $value) {
echo $value->name . "<br />";
echo $value->owner . "<br />";
echo $value->date . "<br /><br />";
}
} else {
echo 'No data found.';
}
If you want to set up the connection in your main.php you can do the following:
//This section goes in the main.php file
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'db_name');
define('DB_USER', 'root');
define('DB_PASS', 'password');
//You can then call the defined constants like this
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

How to get a list of databases?

I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}

Unable to execute MYSQL query inside a PHP function

PHP:
function generate_uid() {
$uid = mt_rand();
$sql = "SELECT user_id
FROM user_registration";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability = TRUE;
while($row = mysql_fetch_array($result)) {
if($row['user_id'] == $uid) {
$availability = FALSE;
}
}
if($availability == FALSE) {
generate_uid();
}
}
The error
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8
Error:
But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??
$con is not defined in the current variable scope. You can pass the connection to function as a parameter:
function generate_uid($con) {
...
mysql_query($sql, $con);
}
$uid = generate_uid($con);
Or you can use global:
function generate_uid() {
global $con;
...
mysql_query($sql, $con);
}
$uid = generate_uid();
Or, simply leave the connection variable out, and the last opened connection will be used:
function generate_uid() {
...
mysql_query($sql);
}
$uid = generate_uid();
All of those should work.
To learn more about variable scope, check out the PHP manual on the subject at:
http://www.php.net/manual/en/language.variables.scope.php
You are using $con in your function, but $con is not defined in your function scope.
http://php.net/manual/en/language.variables.scope.php
You need to either
a) Pass $con to your function or
b) Set $con as a global
c) Not use $con at all eg.
if (!mysql_query($sql))
however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don't specify a connection it will use the last connection opened.
Inside your function, your MySQL connection doesn't exist. You either need to pass it in, or use the global keyword:
$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function generate_uid()
{
global $con;
$uid = mt_rand();
$sql="SELECT user_id FROM user_registration";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability=TRUE;
while($row = mysql_fetch_array($result))
{
if($row['user_id']==$uid)
{
$availability=FALSE; }
} if($availability==FALSE) { generate_uid(); }
}
while($row = mysql_fetch_array($result))
You can't use that if you plan to use $row as an associative array. Use:
while($row = mysql_fetch_assoc($result))
instead.
EDIT
MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.

Categories