Unable to execute MYSQL query inside a PHP function - php

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.

Related

Change code to link mySQL into a function

I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.

Getting errormessage only if using function in MYSQL

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

Accessing from another function an extracted row from an sql table

I have a php auxiliary function called extractFromID() in a file called auxiliary.php which queries a database for a specific line in a table which has a specific ID value and then extracts all the columns from that line.
function extractFromID() {
$connect = mysql_connect("localhost", "root","") or die ("erro a abrir a ligação.");
mysql_select_db ("hospitaldatabase");
$query = 'SELECT * FROM ' .$_SESSION['listtype']. ' WHERE (ID_' .$_SESSION['listtype']. '="'.$_SESSION['id'].'")';
$results = mysql_query($query) or die(mysql_error());
while($rows = mysql_fetch_array($results){
extract($rows);
}
}
From another file, I am trying to access the variables extracted by the function extractFromID() from $rows using
<?php
include('auxiliary.php');
extractFromID();
Although, I seem to be unable to access the extracted values, since I get undefined index errors. What am I doing wrong?
You need to understand variable scope. When you declare a variable inside a function, its scope is limited to that function. You can expand its scope by declaring it to be $GLOBAL but, in your case, the best solution is to return the values you want to use
function extractFromID() {
$connect = mysql_connect("localhost", "root","") or die ("erro a abrir a ligação.");
mysql_select_db ("hospitaldatabase");
$query = 'SELECT * FROM ' .$_SESSION['listtype']. ' WHERE (ID_' .$_SESSION['listtype']. '="'.$_SESSION['id'].'")';
$results = mysql_query($query) or die(mysql_error());
$data = array();
while($rows = mysql_fetch_assoc($results)){
$data[] = $rows;
}
return $data;
}
$myvars = extractFromId();
echo $myvars[0]['fieldname'];
As for undefined variables, it could be you've not called session_start() at the top of your pages before setting your $_SESSION variables. That would mean they are undefined.

PHP MySQLi select function not execute

I'm trying to call my function, but she's wrong.
I believe it is in connection variable.
Connection:
$conn = mysqli_connect('','','', '');
if(mysqli_connect_errno()) {
header("Location: error.php");
exit();
}
Function:
function t_car($id) {
global $conn;
$s_t_car = "SELECT *
FROM t_car
WHERE session='$id'";
$s_t_car_return = mysqli_query($conn, $s_t_car) or die("Erro SQL.".mysqli_error());
return $s_t_car_return;
}
Call Function:
$s_t_car_return = t_car($conn, $_SESSION['session_client']);
if(mysqli_num_rows($s_t_car_return )!=0) {
while($r_t_car = mysqli_fetch_array($s_t_car_return )) {
}
}
Error:
Catchable fatal error: Object of class mysqli could not be converted to string
At first you need to enter your settings from your MySQL server (mysql db).
$connection = mysqli_connect("HOSTNAME","USERNAME", "PASSWORD","DATABASE");
You can then use an if statement to check if the connection to the server has been made, if so, continue execution of following code, otherwise die();
If you want to fetch the data see below here:
$res = $connection->query("SELECT finger FROM hand WHERE index = 3");
while($row = $res->fetch_array())
{
print_r($row);
}
mysqli_query() returns a result. You have to fetch the result to do something with it.
$res = mysqli_query($conn, $s_t_car) or die("...");
$s_t_car_return = mysqli_fetch_row($res);

PHP undefined variable that should clearly be defined

I am wondering how $link can be undefined. It is a global inside class cdb.php and is set when the mysql connect is called. If it were undefined, when mysql connect was called, it would die because I have coded it this way.
<html>
<head>
</head>
<body>
<?php
function justGetCSNumbers($input)
{
$input = preg_replace('/[\D]/',"",$input);
$sp = preg_split("/,/",$input);
$numbs = preg_grep('/^(\d+)(,\d+)*$/',$sp);
$csv = implode(",",$numbs);
#echo $csv;
return $csv;
}
function queryDB($cleaned)
{
$split = preg_split('/,/',$cleaned);
$resAy = array();
for($i=0;$i<count($split);$i++)
{
if((strlen($split[$i])>5)&&(strlen($split[$i])<10))
{
$resAy[$i] = "uid='$split[$i]'";
}
}
if(count($resAy)>0)
{
$q = 'SELECT * FROM userbase WHERE '.$resAy[0];#.$whereclause;
echo '<br/> query: '.$q.'<br/>';
connectDB();
return mysql_query($q,$link) or die("Couldn't complete query ".mysql_error($link));
}
}
function find(){
$p = $_POST['userToQuery'];
if(isset($p))
{
$csv = justGetCSNumbers($p);
$found= queryDB($csv);
}
}
include('cdb.php');
find();
?>
Sorry for the poorly formatted code, using vi.
My apache2 error log shows that the variable $link is undefined when i use it here, even after calling connectDB(); which is the code that does a mysql_connect and therefore sets up the link.
'mysql_error() expects parameter 1 to be resource, null given'
I refactored my code so the link would be defined (this version), but somehow I am having trouble.
[EDIT]
Here is the cdb.php class:
<?php
function connectDB()
{
global $link;
$uname = 'site123';
$pass = 'abc123';
$loc = "localhost";
$link = mysql_connect($loc, $uname, $pass) or die("Couldn't connect to the DB");
$dbname = 'jagrail';
$db = mysql_select_db($dbname,$link);
if(!$db)
{die("Failed to select db");}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
#return $link;
}
?>
EDIT:
Add:
global $link;
to the top of the queryDB() function, so that it knows $link is a global variable, rather than just a local.

Categories