0

I have an issue when executing the sql query.I am explaining my code below.

complain.php:

require_once("./include/dbconfig.php");
if($_REQUEST['typeOfApp']=="WEB"){
        $sent_form="Web";
        $ticket_id=generateTicketId('W1');

    }

function generateTicketId($code){
        $sql="select * from db_ticket order by id desc ";
        $qrylast=mysqli_query($con,$sql);
        echo mysqli_num_rows($qrylast);exit;
}

Here i am trying to check the number of rows.But I am not getting anything.I am giving my dbconfig.php below.

dbconfig.php

$con = new mysqli("localhost", "root", "****", "************"); 
if ($con->connect_error)die("Connection failed: "); 

Here i need to check the no of rows present inside the table.Please help me.

Saty
  • 22,443
  • 7
  • 33
  • 51
  • 3
    you should add a call to `global $con` and do `return mysqli_num_rows($qrylast);` and remove the `exit` for `generateTicketId` function – roullie Jan 27 '16 at 09:26
  • Try to add a DB name to your query. Like `select * from DB.db_ticket ...` where "DB" is your real database name. Also check for mysqli errors: `var_dump(mysqli_error($con));`. – ksimka Jan 27 '16 at 09:27
  • 4
    You have a variable scope problem, you should send the connection to your function as a parameter. For more information: http://php.net/manual/en/language.variables.scope.php and http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and – jeroen Jan 27 '16 at 09:31
  • You seem to double check your code again. Still many problems – Jonny Vu Jan 27 '16 at 09:34
  • Ok,simply passes `$con` as parameter inside the function gave me the result. –  Jan 27 '16 at 09:34
  • By the way, generating an id based on the row-count is a very bad idea. What if two visitors run the script at the same time? And if rows are deleted, you will be generating duplicate id's. You should insert a row and use the inserted auto-increment of the database instead. – jeroen Jan 27 '16 at 10:04

1 Answers1

0

You need to define your connection variable global so you have to access in inside your function OR you need to pass it in function parameter

require_once("./include/dbconfig.php");
//global $con;
if($_REQUEST['typeOfApp']=="WEB"){
        $sent_form="Web";
        $ticket_id=generateTicketId('W1',$con);// pass connection variable

    }

Pass your $con variable as parameter and function need return value

function generateTicketId($code, $con) {
    $sql = "select * from db_ticket order by id desc ";
    $qrylast = mysqli_query($con, $sql);
    $rows = mysqli_num_rows($qrylast);
    if($rows>0){
        return $rows;
    }else{
        return FALSE
    }
}

http://php.net/manual/en/language.variables.scope.php

Saty
  • 22,443
  • 7
  • 33
  • 51