Jump to content

Help with a small script


shmideo

Recommended Posts

Hi, could I have some help with this code please?

 

Getting: "Fatal error: Call to undefined function chn() in ......"

 

Thanks

 

<?php
  $mysqli = chn("localhost", "root", "") or
  die("Connect failed : " . mysql_error());
  mysql_select_db("jm_db");

  $result = mysql_query("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");

 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  echo ($row["channel"]);
}
  mysql_free_result($result);
?>

 

Link to comment
Share on other sites

It sounds like the chn() function used here is undefined:

$mysqli = chn("localhost", "root", "")

Is the function defined in some external script? If so, has that script been imported into the script you're working on?

 

If that function isn't defined anywhere, you need to define it or switch to mysql_connect(). More information can be found here:

http://php.net/manual/en/function.mysql-connect.php

 

Also, in case you're not aware, the mysql_* functions have been deprecated. At some point you'll need to switch to PDO or MySQLi. More information can be found here:

http://php.net/manual/en/mysqlinfo.api.choosing.php

Link to comment
Share on other sites

Did YOU create this code?  Or did you foolishly copy it from somewhere without doing any learning first?  Either way - obviously your attempt to call that function (chn) needs to be corrected.  Either find out (from your code sourcer?) what the function does and replicate it, or dump it and read up on how to establish a db connection.

 

I suggest reading and learning since that can only HELP you in the long run.

Link to comment
Share on other sites

@ginerjm

If you're not going to be helpful to people, you might want to stray from trying to insult their codes like someone on this forum does. You might just get a taste of your own medicine.

 

@shmideo

I don't believe there's any kind of function that's named "chn".

 

In addition, if you're just trying to connect to a database, you might want to not mishmash old deprecated libraries with new libraries. Using both mysql_ and mysqli_ together won't work. There are actually 2 ways of connecting to a database. Most typical way is the procedural way since I've been seeing that a lot with people trying to switch over to the new mysqli.

 

The first one is obivously mysqli_connect and the second one is new mysqli. The only thing I don't like about mysqli_connect is you have to add another line just to connect to your database while you can just do it with one with the new mysqli.

 

Here's a sample for the new mysqli.

<?php
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASSWORD", "password");
define("DB_DATA", "database");

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATA);
if($mysqli->connect_errno()) {
	printf("Connect failed: %s\n", $mysqli->connect_error());
	exit();
}

$query = $mysqli->query("");

Here's a sample for mysqli_connect.

<?php
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASSWORD", "password");
define("DB_DATA", "database");

$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATA);
if(mysqli_connect_errno()) {
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
}

$query = "...";

mysqli_query($mysqli, $query);
Link to comment
Share on other sites

Yes I did switch to using 'mysqli' as 'mysql_connect' it gave an error.

 

Perhaps I'm missing something, but the posted code uses MySQL functions. To use MySQLi, you'll need to change functions like mysql_query() to mysqli_query().

 

 

 

Regarding the undefined function, I don't use this anywhere else, but it seems to expect a parameter in this line "$mysqli = chn("localhost", "root", "").

 

Hmm...do you see an error that suggests the chn() function call is missing a parameter? Based on your original post, the chn() function is undefined. Has something changed?

Link to comment
Share on other sites

Thanks guys. I am fairly new to PHP and MySql and have been paying around with this code for a few days now!. Although I did borrow a snippt " while ($row = mysql_fetch_array", the original posted code I did.

 

I think I've progressed, now getting "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in".

 

Code:

 

<?php

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATA", "jm_db");

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATA);
if($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error());
    exit();

}
$query = mysqli_query($mysqli,"SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");

while ($row = mysqli_fetch_array($query, MYSQL_ASSOC)) {
   $result = $row[0] ;
   echo ($row["channel"]);
}

?>

 

Link to comment
Share on other sites

The message indicates that  the query failed.  You didn't get back a 'resource' as expected, you got instead a value of False(ie, a Boolean).  This would have been detected had you done the proper thing and tested the results before blindly trying to fetch the results.

Link to comment
Share on other sites

Thanks guys. I am fairly new to PHP and MySql and have been paying around with this code for a few days now!. Although I did borrow a snippt " while ($row = mysql_fetch_array", the original posted code I did.

 

I think I've progressed, now getting "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in".

 

Code:

 

<?php

 

define("DB_HOST", "localhost");

define("DB_USER", "root");

define("DB_PASSWORD", "");

define("DB_DATA", "jm_db");

 

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATA);

if($mysqli->connect_errno) {

    printf("Connect failed: %s\n", $mysqli->connect_error());

    exit();

 

}

$query = mysqli_query($mysqli,"SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");

 

while ($row = mysqli_fetch_array($query, MYSQL_ASSOC)) {

   $result = $row[0] ;

   echo ($row["channel"]);

}

 

?>

You're using OOP with procedural. You can't do that. It's either stick with procedural or stick with OOP. You're best bet is to stay with procedural since you're more familiar with that.

Link to comment
Share on other sites

 

You can.

function mysqli_query($conn, $sql)
{
    return $conn->query($sql);
}

That's procedural to OOP. He's doing OOP to procedural which doesn't work. You can't use new mysqli if you're using procedural. You can only use mysqli_connect if you're using procedural and if you're using OOP, you can only use new mysqli. Both achieve the same thing. It's just different coding styles that's different.

 

Edit: He's getting the Boolean error because he's combining OOP with procedural. Since OOP doesn't have that kind of coding style. mysqli_fetch_array doesn't work. It has to be $mysqli->fetch_array(MYSQLI_BOTH) if you want to use both associative and numerical arrays, but you can use $mysqli->fetch_array(MYSQLI_ASSOC) if you want to use associative arrays. If you want numerical arrays, you can use $mysqli->fetch_array(MYSQLI_NUM)

Edited by LeJack
Link to comment
Share on other sites

LeJack, Will you please explain why I get the same results with these two sets of code if it can't be done

$db = mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
$res = $db->query("SELECT COUNT(*) FROM votes");
list($count) = $res->fetch_row();
echo $count;                                        // 182685
$db2 = new mysqli(HOST,USERNAME,PASSWORD,DATABASE);
$res = mysqli_query($db2, "SELECT COUNT(*) FROM votes");
list($count) = mysqli_fetch_row($res);
echo $count;                                        // 182685
Link to comment
Share on other sites

I've done some reading up and a couple of tutorials and have come up with this. It's the same goal except I put it into a 2 field form "Date" and "Channel".

The connect to database is in a separate .php which the main code includes. The connect to db code does not get errors and when I run the main code and fill in the form I get blank white screen. I have error reporting on within the code but still blank results.

 

Have checked php error log within WAMP and nothing. It seems the html is being executed but not the PHP code within?

<html>
<head>
<title>Call Statistics Test</title>
<style type="text/css">

table {
	background-color:#FCF;
	}

th {
	width: 150px;
	text-align: left;
}

</style>
</head>
<body>

<h1>Calls Search</h1>

<form method="post" action="search1.php">
<table>Search Call Date: <input type="text" name="calldate" /></table>  

<table>Search Channel: <input type="text" name="channel" /></table>

<input type="submit" />

</form>    

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);  

if (isset($_POST['submitted'])) {
	
// connect to the database
include('connect1.php');

$calldate = $_POST['calldate'];
$channel = $_POST['channel'];
$query = "SELECT * FROM asterisk_cdr WHERE $calldate LIKE '%$calldate%' AND $channel LIKE '%$channel%'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
$num_rows = mysqli_num_rows($result);


echo "$num_rows results found";
echo "<table>";
echo "<tr> <th>Channel</th>";

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

	echo "<tr><td>";
	echo $row['channel']."<br />";
	echo "</td>";

}

	echo "</table>";
	
}

?>

</body>
</html>
Link to comment
Share on other sites

I tried that and now getting the error; "error getting data" (from line 43 mysqli_query...). Nothing in the php error logs.

The two table columns I'm trying to read are 'calldate' and 'channel'. Search criteria used: 2014-11-01 (calldate) and SIP/4546975289 (channel) which exist within asterisk:cdr table.

Link to comment
Share on other sites

On this line 

$query = "SELECT * FROM asterisk_cdr WHERE $calldate LIKE '%$calldate%' AND $channel LIKE '%$channel%'";

change 

$calldate LIKE '%$calldate%' AND $channel LIKE '%$channel%'

to

calldate LIKE '%$calldate%' AND channel LIKE '%$channel%'

 

 

You want to use the database table names there NOT the variables from the form. 

Link to comment
Share on other sites

The code works great now but how can I validate for blank fields in the form? Have tried as below but it only checks when first run then ignores.

 

if(!isset($calldate) || trim($channel) == '')
{
   echo "You did not fill out the required fields.";

        }

Link to comment
Share on other sites

Check out the difference between empty() nd isset()

I like to use empty() on the text inputs and isset() on the checkboxes

 

something like

// Validate the input calldate:
	if (!empty($_POST['calldate'])) {
		$calldate = mysqli_real_escape_string ($dbc, $_POST['calldate']);
	} else {
		$calldate = FALSE;
		echo '<p class="error">You forgot to enter a date!</p>';
	}
Link to comment
Share on other sites

The code:

<?php

error_reporting(E_ALL | E_NOTICE);
        ini_set('display_errors', '1');  

if (isset($_POST['submitted'])) {
	
// connect to the database
include('connect1.php');

$calldate = $_POST['calldate'];
$channel = $_POST['channel'];
$submitted = $_POST['submitted'];
$duration = 'duration';

// Validate the input calldate:
	if (!empty($_POST['calldate'])) {
		$calldate = mysqli_real_escape_string ($dbc, $_POST['calldate']);
	} else {
		$calldate = FALSE;
		echo '<p class="error">You forgot to enter a date!</p>';
	}

$query = "SELECT * FROM asterisk_cdr WHERE calldate LIKE '%$calldate%' AND channel LIKE '%$channel%'";
$result = mysqli_query($dbcon, $query) or die('Error getting data');
$num_rows = mysqli_num_rows($result);

echo "$num_rows calls found for $calldate";
echo "<table>";
echo "<tr> <th>Call Details: </th>";


while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

	echo "<tr><td>";
	echo $row['calldate'];
	echo "</td>";

}

	echo "</table>";
	
}

?>
</th>
  </tr>
</table>
</body>
</html>
Link to comment
Share on other sites

Replace $calldate=$_POST['calldate'];

With the code I posted

But change $dbc to your variable you are using in your connection script.

 

Then you also need to add a check in there to only execute the query if the conditions are met

Like

If($calldate){

Add Db query here

}

 

Sorry on my phone know so if you can try and get that to work great

Or I can post more later at my computer

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.