How to use mysql_errno() inside own error handling function? - php

I want to use my own error handling and my first thought was this:
// db connection
$conn = conn();
if(!$conn)
$aErrors[] = 'Fout: Geen database verbinding!';
function db_error($conn)
{
if(mysql_errno($conn) == 0)
return true;
else
{
// log! and global $aErrors[] = mysql_errno($conn)
return false;
}
}
$q = "SELECT
xusername, email
FROM
terra_user
WHERE
ID = '".$_GET['ID']."'
LIMIT 1";
$exec = mysql_query($q);
// error check
if(db_error($exec))
{
echo'teeeeeest!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
But I get the next error:
Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in xxxx
In this case, mysql_erro() returns a number > 0, so it looks OK, except that the link source is not OK?
If I use mysql_errno($conn) I get :
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in xxxxxx
In this case, mysql_erro() returns 0!
For this code I have changed one field with a wrong name. Put an extra x for username:)
$_GET['ID'] is already tested with ctype_digit($_GET['ID'])
What am I doing wrong here?

I see no point in such a function at all. You have $exec for your error "handling", that's enough.
// db connection
$conn = conn();
if(!$conn) {
$aErrors[] = 'Fout: Geen database verbinding!';
}
$q = "SELECT xusername, email FROM terra_user WHERE ID = ".(int)$_GET['ID']." LIMIT 1";
$exec = mysql_query($q) or trigger_error(mysql_error());
// error check
if(!$exec))
{
$aErrors[] = 'Fout: Geen database verbinding!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
Though I see no point in collecting errors into array. if it's critical error, no need to wait for the other - only one is enough. if it's not a critical error - why disturb a user with it?

Related

PHP NOTICE:Undefined offset 1

I am facing a problem that undefined offset :1. I can't understand that what type of error it is. Can anyone tell me that why such error occurs in php
<?php
$host="localhost";
$dbusername="root";
$dbpassword="";
$dbname="school";
$conn=mysql_connect($host,$dbusername,$dbpassword) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
if(isset($_POST['submit']))
{
$cls=$_POST['hhcls'];
{
{
{
$query=mysql_query("select * from stu_class where class='$cls'",$conn);
while($data=mysql_fetch_row($query))
{
$r1=$data[0];
$r=$_POST[$r1]; //THIS LNE ERROR
echo $r;
$query1="update stu_class set rollno=".$r." where ad_no=".$r;
$sql_query1=mysql_query($query1) or die(mysql_error());
if($sql_query1)
{
echo "<script type='text/javascript'>alert('Students Details Updated Successfully');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Updation Failed');</script>";
}
}
}
}
}
}
?>
I am getting error while passing data to another query
Of course )
Look:
$query = mysql_query("select * from stu_class where class='$cls'", $conn);
// Now we got not query, but result of this query in $query
while ($data = mysql_fetch_row($query)) {
// Every iteration we will have in $data array (not associated)
// of fields (next row from database)
$r1 = $data[0];
// After this line we have value of first column of current line in $r1
// usually this is integer ID field and if first ID in database is 1,
// then $r1 = 1
$r = $_POST[$r1]; //THIS LNE ERROR
// here you trying to set $r = $_POST[1] because $r1 = 1
// but you have no any POST variable with key 1.
When you trying to get some array member that doesn't exist, you will get notice "Undefined offset %key%". In strict mode you will get exception.

$connection->query($mysearch) not working

The error occurs like that, when i try to connect to DB to search something, it doesn't connects... here is the code below
$connection = new mysqli($db_server,$db_user,$db_pass,$db_name);
if($connection->connect_errno)
{
die ("Connection Failed");
}
$selcap = "SELECT * FROM captcha_codes ORDER BY RAND() LIMIT 1";
$seldcap = $connection->query($selcap);
if($seldcap === true)
{
while ($capdata = $seldcap->fetch_array(MYSQLI_BOTH))
{
$imglink = $capdata['image'];
$idcap = $capdata['id'];
$codecap = $capdata['code'];
}
} else {
$msgreg = "Couldn't connect to Captcha, please contact admin!";
}
The result is Couldn't connect to Captcha, please contact admin!
Use the less strict == comparison here: if($seldcap === true), that should solve the issue.
So the condition would look like: if($seldcap == true)
As mentioned by others, you could also check the number of results as well.
See the docs for mysqli::query() for more information on the results of that function.
If you want to check either query returns result or not use num_rows :
$seldcap = $connection->query($selcap);
if($seldcap->num_rows > 0)
{
//your while stuff
}
else{
//your error stuff
}

Query Checking for Existence - PHP

I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in (...) on line 4

Here is my snippet.
I've checked some other questions similar to my error, but so far I can't get it solved.
<?php
function user_exists ($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(user_id) FROM users WHERE username = $username"), 0) == 1) ? true : false;
}
?>
You should split your code in some more lines to handle those errors or special cases. mysql_query will return zero to n rows or an error if it occurs. The returned resource will therefore only be true on non-error queries. This can be used to handle such situations like follows.
At first build and execute query, next process the resource.
$query="SELECT COUNT(user_id) FROM users WHERE username = ".$username;
$result = mysql_query($query);
u may use the following to determine what is going on in case of an error:
if(!$result) die("SELECT failed: ".mysql_error());
or these idea to handle the problem
if (!$result=mysql_query($query)) {
return false; // or similar operation
}
if (mysql_num_rows($result)!=1){
return false;
}else{
return true;
}
This could happen, when mysql_query returns false, if it fails for some reason. So you should split this into multiple statements and check the return values
$sql = "SELECT COUNT(user_id) FROM users WHERE username = $username";
$result = mysql_query($sql);
if ($result === false) {
// error handling
return false;
}
return (mysql_result($result, 0) == 1) ? true : false;

problem with fetching results from mysql via php function

can some one point out the problem with this code? It supposed to fetch data from mysql but it returns blank. Here is the full code.
<ul class="list">
<?php
require("object/db.class.php");
error_reporting(0);
function entry_tickets() {
if($_SESSION['dojopress_global:root'] == false) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/apps/gnome-keyring-manager.png" />Access denied</p></li>
ENTRY_TICKET;
} elseif($_SESSION['dojopress_global:root'] == true) {
$q = "SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC";
$r = mysql_query($q);
if ( mysql_num_rows($r) == 0 ) {
$entry_ticket .= <<<ENTRY_TICKET
<li><p><img src="http://cdn1.iconfinder.com/data/icons/humano2/32x32/status/dialog-information.png" /> Nothing to display</p></li>
ENTRY_TICKET;
} elseif ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_array($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
function note_type($type) {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return ($type);
}
$entry_ticket .= <<<ENTRY_TICKET
<li><p> $athor, note_type($type)</p></li>
ENTRY_TICKET;
return $entry_ticket;
}
}
}
}
echo entry_tickets();
?>
</ul>
<div style="clear:both;height:10px;"></div>
sorry forgot db.class.php
<?php
session_start();
//connect.php
$host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "au";
$connectClass = mysql_connect("$host", "$db_user", "$db_pass") or die ("Couldn't establish connection to database server.");
$dbObject = mysql_select_db("$db_name", $connectClass) or die ("Couldn't select database.");
?>
error reporting disabled error code
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\wamp\www\ageis\note.php on line 22
Your mysql syntax looks bad. You have:
SELECT * FROM `notice` ORDER BY nid LIMIT 12 DESC
try
SELECT * FROM `notice` ORDER BY nid DESC LIMIT 12
Erik's comments should have pointed you in the right direction, however:
Figure out where PHP logs errors. Either turn up php's error reporting level so you see more errors, or start tailing your apache error_log
You should always check for errors after running mysql_query and do some sort of logging on failure. This is probably best accomplished by writing a wrapper function for mysql_query that does this, or using a 3rd party db wrapper that has already solved this problem.
You're redefining function note_type every time through your while loop. You have a return call outside the function, below it. Really I can't see how this is even syntactically correct. It looks like you have a large problem with mismatched brackets.
As for an actual database issue, you should check mysql_error() if no rows return from the call because it's likely something went wrong.
Also I recommend using PDO which is a true database class instead of the native function based ones.

Categories