Having a repetitive code like so:
$SQL = " INSERT INTO ... ";
mysql_query($SQL, $conexion);
$error = mysql_error();
if($_ADM['id_user']==1) {
if( ! empty($error)) {
$debug = array(
'message' => "SQL Error in news_edit module.",
'line' => '177',
'error' => $error,
'SQL' => $SQL
);
exit(print_r($debug));
}
}
This is a common code, that repeats its self every time $SQL changes. What I'm trying to achieve is a way to debug if any error occurs and as I you can see, I have the line parameter which contains the number line where last mysql_query was executed, but I have to type that manually and every time I add code before it, the line parameters needs to be changed with the new line value.
Is there any way of identifying where was last time mysql_query executed? Any other way of improving the code above?
try using
'line'=> __LINE__,
its a magic constant which displays the current line of the file..
I think what you want is debug_backtrace function.
Check the manual for specs:
http://php.net/manual/en/function.debug-backtrace.php
Related
Something really weird is going on here. I have this method for mysqli query.
public function select($options) {
$default = array (
'table' => '',
'fields' => '*',
'condition' => '2',
'order' => '1',
'limit' => 50
);
$options = array_merge($default,$options);
$query = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
}
Once the query get executed I get $rows and everything works like a charm. But then when I try to get specific key in array I get the "Query failed:" without specific message :S
$options = array(
'table' => 'settings',
'fields' => 'setting_wall_post,setting_status_tag,setting_photo,setting_like,setting_comment',
'limit' => '1',
'condition' => "setting_id = 6",
);
$check = $this->mysql->select($options);
print_r($check);
$check = $check[0];
if($check["setting_wall_post"]) //if I comment out this IF block it works :(
$this->scope["wall_post"] = "publish_stream";
Also I've tried to close mysqli connection and then I get
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli
this IF block is acting like it works with mysqli :S
So the question is, what is the issue here? Why can't I access to "setting_wall_post"? I guess that part is the problem since it works if I comment out that IF block.
Edit. What a silly I am, overlooked such a typo: $this->conn have to be used instead of undefined $mysqli.
That's why one should always have error reporting no less than E_ALL
The code you posted just cannot cause this kind of error.
Change your error reporting code to this one
} else {
throw new Exception($this->conn->error);
}
this way you will have a stack trace which will show the chain of calls, pointing to the place of code that caused particular error.
BTW, the whole function looks unusable and error prone to me. it is open to injection and require more code than a conventional SQL
Going through a PHP MySQL tutorial and switching the PHP out for PDO; at any rate, my query is coming up blank.
$get_cat = $that->dbh->query("SELECT `cat_name`, `cat_desc` FROM `categories`");
if(isset($get_cat))
{
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
{
printf("
<tr>
<td>".$row['cat_name']." : ".$row['cat_desc']."</td>
</tr>
");
}
}
else
{
echo '<tr><td>return is false</td></tr>';
}
$That refers to:
include('db.php');
$that = new lib();
OLD:
So, why is my query blank? Before putting the die in it would return Boolean and give in an error in the loop with the die in it just comes up blank. The categories table has data in it and the page is refreshed on submission for new entries.
NEW:
Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\forum\create_category.php on line 36
Line 36 is the while loop line.
mysql_fetch_array is not PDO. You would need something like:
while($row = $get_cat->fetch(PDO::FETCH_ASSOC))
To get your rows.
Nor can you use mysql_error() to get the error. You could use for example $that->dbh->errorInfo() but you should look into exceptions for a more robust way to catch all errors.
Edit: You should check what the error is. Using isset is pointless as you have just assigned a value to it, so it will always be set.
You need to tell PDO to throw errors.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$res = $that->dbh->query("SELECT cat_name, cat_desc FROM categories");
while($row = $res->fetch())
{
echo "<tr><td>$row[cat_name] : $row[cat_desc]</td></tr>\n";
}
run your code, read the error message and take appropriate action
Don't forget to add the first line into your db.php file, to make the setting permanent
Your query is incorrect -- is this what you're trying to do?
SELECT `categories`.`cat_name`, `categories`.`cat_desc` FROM `categories`
Hard to know without seeing you table structure.
I am having a problem when trying to access some functions in my mysql class. The function I have to connect to my database is as follows:
function connect_DB() {
$this->connection = mysql_connect($this->dbURL, $this->dbUser, $this->dbPass) or trigger_error('Connection failed: ' . mysql_error($connection), E_USER_ERROR);
$this->db = mysql_select_db($this->dbName, $this->connection) or trigger_error('Database selection failed: ' . mysql_error($db), E_USER_ERROR);
}
And I create my mysql object using this:
$dbConf = new StoreConfDB();
$dbConf->connect_DB();
Now I have a function that is supposed to grab all of the column names from a specified table. Code:
function get_db_columns($table) {
global $dbConf;
print_r($dbConf->get_db());
$result = $dbConf->query_DB_resource('SELECT * FROM ' . $table);
for($i = 0; $i < mysql_num_fields($result); $i++) {
$meta = mysql_fetch_field($result, $i);
$fields[] = $meta->name;
}
mysql_free_result($result);
return $fields;
}
But I am getting errors, such as:
Warning: mysql_query(): 5 is not a valid MySQL-Link resource
And if I try to remove the connection argument from the mysql_query call I get this:
Notice: Could not run query: No database selected in ...
Now I am running a debugger and have pinpointed what the problem is (I think). When the class works, the connection variable is set to: resource id='5' type='mysql link'
But when it calls the query function in the mysql class from inside the get_db_columns() function the connection variable is: resource id='5' type='Unknown'
So somehow the connection variable gets messed up even though both of the connection variables should be the same thing? (from $dbConf)? I've tested this function in 2 different places, it works in one and not the other! Please help!
#footy:
A print_r on $dbConf returns:
StoreConfDB Object ( [dbURL] => localhost [dbUser] => root [dbPass] => [dbName] => db1 [connection] => Resource id #5 [db] => 1 )
The query_DB_resource function:
function query_DB_resource($query) {
$sql_query = mysql_query($query) or trigger_error('Could not run query: '. mysql_error());
return $sql_query;
}
I noticed a couple of issues:
You have mysql_error($connection) and mysql_error($db). Those aren't valid parameters. You should be using $this->connection in both cases. That will give you better error output.
Normally, it doesn't terribly matter if you pass in a connection resource to mysql_query, but in this case you may want to: mysql_query($query, $this->connection). While I can't say that that is a guaranteed fix, it is likely to help.
Oh, and BTW -- every time someone uses global God kills a kitten. It's true. He told me. Either that or I had some bad nachos. (Yes, I'm a zealot on this issue. It's a good thing. trust me)
Regardless, if you need a variable inside of a function either pass it in, or make a property of a new class (make the StoreConfDB a Singleton? Make it accessible by factory method? You have a number of choices) -- avoiding global as a habit removes something nasty called unexpected side effects.
Before anyone jumps on me, I have found a similar issue here, but unfortunately their answer does not seem to apply to my problem.
I have created a function called sqlReturn() in order to more easily produce an error (with standard output) should a query go wrong. The code is below:
function sqlResult($query)
{
return mysql_query($query)
or die("SQL Query: " . $query . "<br />SQL Error: " . mysql_error());
}
As you can see, it just outputs an error in the way I like, and it saves me a bit of effort in coding along the way. However, while this has been working in most cases (eg. situations where I use SELECT or INSERT), it is throwing the following error:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in /var/www/login/login_submit.php on line 42
It is returning 1 instead of a resource. If, instead of calling that function (which is in a separate php file), I simply use the line of code in the same file without a return statement
(ie. $sqlResult = mysql_query($sqlQuery) or ... etc.), it returns a resource as normal.
In case it's relevant, my SQL query is also below:
$sqlQuery =
"SELECT userID, username, password, access_level
FROM users
WHERE username = '{$username}'
AND (password = '{$password_sha1}' OR password = '{$password_sha256}')";
Any input on this would be appreciated.
Thanks,
Paragon
Sneaky suspicion that binding rules are kicking in here. PHP may be seeing your function as
return (mysql_query(...)) or die(...);
and return before ever seeing the die(). Try rewriting like this
function sqlQuery(...) {
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error(...));
}
return $result;
}
so there's no chance of any mis-parsing.
That's the first time i get an error like this one, let me explain :
Here is my code :
function printSiteIndexedItems($co, $id){
global $allSections;
foreach($allSections as $aSection => $aSectionName){
$tr = $co->prepare("SELECT COUNT(id) FROM ". $aSection ." WHERE site=:id AND valide=1");
$tr->bindParam(':id', $id, PDO::PARAM_INT);
$tr->execute();
if($indexedItems = $tr->fetchColumn()) echo '<p>'. $aSectionName .' : '. $indexedItems .'</p>';
}
}
The first iteration works just fine, it prints what i want (a category name and the number of elements in it).
But after that first iteration, i get this classic error :
Fatal error: Call to a member function bindParam() on a non-object in
Indeed, $co is a valid PDO object as it works for the first iteration. But it seems that as soon as we enter the second one, it no longer is ? :o
I'm kinda new with PDO, so maybe it's a normal behavior i didn't acknowledge yet. Please help ! =)
Looks like $co->prepare... returns FALSE for at least one of the stamtents you try to prepare.
Either test if ( !$tr ) .... or set $co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); to get an exception when PDO encounters an error.
I think that $co->prepare returns a failure (false probably) which suggests that the statement is invalid. Make sure that $aSection is not empty.
You also shouldn't be putting $aSection to the query like you do now as you might encounter a SQL injection problem if $aSection comes from a user input.
Most likely $aSection is invalid. As you didn't provide the data it is hard to guess. please learn about PDO error handling: http://de.php.net/manual/en/pdo.error-handling.php
something like this code should help:
foreach($allSections as $aSection => $aSectionName){
$tr = $co->prepare("SELECT COUNT(id) FROM ". $aSection ." WHERE site=:id AND valide=1");
if (!$tr) {
print_r($co->errorInfo());
continue;
}
$tr->bindParam(':id', $id, PDO::PARAM_INT);
$tr->execute();
if($indexedItems = $tr->fetchColumn()) echo '<p>'. $aSectionName .' : '. $indexedItems .'</p>';
}