I am using the following code to parse definitions from a remote website , according to the usernames in my database. I am using simple html dom parser.
//database connection
include 'db.php';
//display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include 'simple_html_dom.php';
//select usernames order alphabetically
$row = mysqli_query($conn, "SELECT user_name FROM (
SELECT *
FROM store
ORDER BY user_id DESC)
AS store ORDER BY user_id ASC");
//echo out definitions of usernames
while($lastusers = mysqli_fetch_array($row)) {
echo '<br>' . $lastusers["user_name"];
echo '<br>Definition:<br>';
$html = file_get_html("https://www.merriam-webster.com/dictionary/" . $lastusers["user_name"]);
$title = $html->find("div.card-primary-content", 0)->innertext;
echo $title;
//save definitions to corresponding username
$save = mysqli_query($conn, 'UPDATE store
SET def = $title,
WHERE user_name = $lastusers["user_name"]'
)
}
My while loop will begin to generate the definitions per username , until certain pages are not found resulting in an error that stops the loop.
Warning:
file_get_contents(https://www.merriam-webster.com/dictionary/colourings):
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in
/app/simple_html_dom.php on line 75 Fatal error: Call to a member
function find() on boolean in /app/test.php on line 18
My question is how to skip over the username that throws the error and continue the loop? Also because their are over 500 usernames , this operation is very intensive , so i'm saving the definitions , and would like to avoid the errors being saved to the database.
You can suppress the warning like shown in the following link
How can I handle the warning of file_get_contents() function in PHP?
Or an other alternative is to write a custom error handler. See this link
PHP: How to use set_error_handler() to properly deal with all errors except notices?
Related
I'm using Wordpress and I'm performing a query which gives me back this error:
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
My query looks like:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
$check_last_conversation = $wpdb->get_results($ss);
$response = print $check_last_conversation;
I'm probably missing or misunderstanding something but if I comment out $check_last_conversation and I print something like "Hello", the error goes away.
This is ok:
global $wpdb;
$session_uid = isset($_POST["session_uid"]) ? trim(strip_tags($_POST["session_uid"])) : "";
$the_data = isset($_POST["the_data"]) ? trim(strip_tags($_POST["the_data"])) : "";
//$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
//$check_last_conversation = $wpdb->get_results($ss);
$response = print 'hello';
So I suppose there is some problems on how I've written my query.
$ss = "select * from ".$wpdb->prefix."vp_pms_messages inner join ".$wpdb->prefix."vp_pms_group_users on ".$wpdb->prefix."vp_pms_messages.id = ".$wpdb->prefix."vp_pms_group_users.message_id and ".$wpdb->prefix."vp_pms_messages.group_id = ".$wpdb->prefix."vp_pms_group_users.group_id where ".$wpdb->prefix."vp_pms_group_users.from_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.from_del = '0' or ".$wpdb->prefix."vp_pms_group_users.to_username = '$session_uid' and ".$wpdb->prefix."vp_pms_group_users.to_del = '0' group by ".$wpdb->prefix."vp_pms_messages.group_id";
Said that, I can't see the error.
My apache_error.log and mysql_error_log.err don't report anything
about.
My tables are empty at now but should they print nothing than produce that error.
Can you please suggest something?
EDIT
I see this error in my console
MySQL table empty
My Wordpress Debug is active like:
My debug.log file (wp-content) is not showing any error in my code.
I've discovered that there is a fatal error in the same file of my query:
PHP Fatal error: Call to undefined function get_bloginfo()
I could check it trough the server php error log. Working on MAMP you can find it here:
MAMP/logs/php_error.log
In my case, Wordpress didn't report it in wp-content/debug.log. So you know. It takes me to the conclusion that my file.php doesn't recognise wordpress hooks and could happen for $wpdb too, throughout my query.
As OP mentioned that he is working on external wordpress script and is not able to access his wordpress functionality. To ensure that you retain your wordpress functionality on your external files, please put the following code, at the start of your external script page.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
The above lines, will include all the wordpress functionality for your script. $path variable stores the path of your wordpress installation folder.
During the development always turn on the error reporting to be aware of warnings notice or fatal errors which can occur very easily if you forget something or miss place something. So better to be aware or errors and turn the error reporting on to see the errors and when in production do disable the error reporting.
go into wp-config.php file and search for : define('WP_DEBUG',false); and change it to define('WP_DEBUG',true);
Even if your query is okay , you will still result to an error , which you will be getting due to incorrect printing of an array:
function get_results of $wpdb , is an function that will return an array as result of multi rows , and for dumping it use :
print_r($check_last_conversation);
or
var_dump($check_last_conversation);
print 'hello; works because it is a string , and $check_last_conversation is an array. Don't wrap the print_r or var_dump or print or echo inside an variable. as they are supposed to print the data inside from variables.
so in case you have more errors , you can look at the errors , by turning the error reporting on.
Sort of going on from Ajit's answer. I was also having issues similar to this that was caused by character collation which was fixed by adding one extra line.
At the top of any php external file that used wpdb I was using the following:
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
You can then use the $charset_collate in your sql statement, e.g.
$sql = "CREATE TABLE `{$wpdb->base_prefix}my_nice_table` (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) $charset_collate;";
Hope that helps!
I have a script that is supposed to display the results of a Postgres query based on a link that the user clicks on a previous page.
For example, when the user clicks on the Title of a project, it directs them to a page that shows them more attributes about the project, which are contained in columns in the database.
I already have the page working where users can click on a Title, but once they click a title, my second page to display the other attributes of the project is not working.
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$row = false;
if (isset($_GET['pid']) && filter_var($_GET['pid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$pid = $_GET['pid'];
require('/var/www/postgres_connect.php');
$q = 'SELECT * FROM public.' + "tblProjects" + 'WHERE ' + "tblProjects" + '.ProjectID = ' + "$pid";
$r = pg_query ($dbconn, $q);
if (pg_num_rows($r) == 1) {
$row = pg_fetch_assoc ($r);
$page_title = $row['ProjectID'];
echo "<div align=\"center\">
<b>{$row['ProjectID']}</b> by
{$row['ProjectTitle']}<br />";
echo '<p align="center">' . ((is_null($row['totalcost'])) ? '(No Cost Recorded)' :
$row['totalcost']) . '</p>';
}
pg_close($dbconn);
}
if (!$row) {
$page_title = 'Error';
echo '<div align="center">This page encountered an error!</div>';
}
?>
Running this script produces the following error:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "20131418" LINE 1: 20131418 ^ in /var/www/html/view_project.php on line 13
Warning: pg_num_rows() expects parameter 1 to be resource, boolean given in /var/www/html/view_project.php on line 14
Now, I don't think the second error is a problem because solving the first error will produce a result of the query and then clear up the second error.
I don't understand what is wrong with the syntax; having $pid at the end of the query returns an integer(20131418) which is being called out as invalid syntax. What can I do to solve this issue?
The correct syntax for the SQL statement is as follows:
'SELECT * FROM public."tblProjects" WHERE "tblProjects"."ProjectID"=' . $pid;
The main reason for this not working in the first place was because of mixed cases in column and table names.
See this answer to a similar question: https://stackoverflow.com/a/12250721/3620249
I had thought the $pid needed to be within the query string (single quotes). However, the variable would not be called unless the query string was double quoted. It then became difficult to manage the mixed cases in the column/table names with quotes as well, so I tried using + to concatenate instead of . as you can see in my question.
Lessons learned:
Concatenate in PHP using .
Variables can be called from outside of a query string using concatenation.
If table/column names contain mixed cases, they must be contained within double quotations
Heres the story,
I am uploading a list of part numbers on text file via gzip, the reading is successful.
The format is:
"DATE"|"TYPE"|"ID"|"FPN"|"PN"|"IOC"|"FIELD"|"OVAL"|"NVAL"
Sample Value :
"2013-09-10 19:19:08"|"DU"|"10161000001354"|""|"ANTX100P001B24003"|""|"Sub-Category 1"|"Metal Antenna"|"PCB Antenna"
Now the scenario is, I loop on each entry to insert it to database and set notifications for users to see an update about that certain part number and get their email to conduct a mailing later in other page.
the loop code is here :
for($x=1;$x<=count($lines)-1;$x++){
$cur_row = trim(str_replace('"','',$lines[$x]));
$cols = preg_split('/\|/',$cur_row);
$query = sprintf('INSERT INTO `notification_details`(`NDATE`, `NTYP`,`NPID`,`NFPN`,`NPN`,`NIOC`, `NFILD`, `NOV`, `NNV`) VALUES(\'%s\',\'%s\',%s,\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')',$cols[0],$cols[1],$cols[2],$cols[3],$cols[4],$cols[5],$cols[6],$cols[7],$cols[8]);
mysql_query($query);
$query = 'SELECT DISTINCT `id` FROM `project_details` WHERE `prod_id` = \''.$cols[2].'\';';
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count>0){
$query = 'SELECT MAX(`NID`) FROM `notification_details`';
$result = mysql_query($query);
$row=mysql_fetch_array($result);
$NID = $row[0];
$query = sprintf('INSERT INTO `read_details`(`NID`, `PID`,`ISREAD`) VALUES(%s,%s,1);',$NID,$row['id']);
mysql_query($query);
}
echo $cols[2].".... Done!<br />";
flush();ob_flush();
}
//EMAIL LISTING BLOCK
echo "Listing E-mails...<br />";
$query = 'SELECT B.`proj_user`, C.`email` '
.'FROM `read_details` A, `project_details` B, `login_details` C'
.'WHERE A.`ISREAD` = 1 '
.'AND A.`PID` = B.`id` AND B.`proj_user` = C.`username` '
.'GROUP BY B.`proj_user`';
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
mysql_query('INSERT INTO `email_details`(`email`,`user`) VALUES(\''.$row[1].'\',\''.$row[0].'\')');
echo $row[1].".... Added!<br />";
}
Heres some runs I did:
Product (193 lines) + full run of the code above = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page
Product (193 lines) + less the Email Block = Successfull
Product (18,000 lines) + full run of the code above = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page.
Product (18,000 lines) + less the Email Block = Internal Server Error + the whole site become under Internal Server Error whenever trying to access other page.
I don't know if it just me or what, but even the server returns internal server error, the products are keep adding on the database (I look at it and try to query a count and it increments) and stops at random point, that point the site is become accessible again. But sometime it doesnt do that.
Any ideas? Thanks in advance.
EDIT :
NID & PID is BIGINT, ISREAD is BOOLEAN, the rest are LONGTEXT
Plus while running, the page is /uploadpcn.php, this code is under /do_upload_pcn.php
so the scenario is that, the whole process is in loading while on /uploadpcn.php and when the process ends, the browser will go to /do_upload_pcn.php showing all echos OR shows internal server errors anytime in the process.
Try to log the loop with each record and you may come to know which particular record is causing the error. You may also apply some try-catch logic. I presume this could be a parsing error.
Another thing to notice is that your first INSERT query does not contains single-quotes around the string data. This could be another issue leading to the error.
Edit:
This query in the code in the question $query = sprintf('INSERT INTOread_details(NID,PID,ISREAD) VALUES(%s,%s,1);',$NID,$row['id']); should be like:
$query = sprintf('INSERT INTO `read_details` (`NID`, `PID`, `ISREAD`) VALUES (\'%s\', \'%s\', 1);', $NID, $row['id']);
I would suggest to use double quotes for constructing queries so that you may easily use single quotes for parameters.
So, I've been having a bit of trouble getting MySQL to work.
My Apache server is up and running, PHP is properly installed, and my MySQL server status is running.
When I call phpinfo() it tells me where the mysql.sock is located, both the folder and file exist.
I'm running OSX 10.8.4
I'm following this tutorial to try to get a grasp of how chats would work: http://www.ibm.com/developerworks/library/x-ioschat/
So when I run my php script, the page loads with errors. I'm new to PHP, and am having a difficult time debugging, installation was particularly troublesome.
So if I keep content-type: text/xml uncommented I get this error:
error on line 2 at column 1: Document is empty
It also tells me that the page is rendered up to the first error, so it makes sense that the page is blank when I load it.
When it is commented, the errors begin to make a bit more sense; however, given my absolute newbish nature to PHP I'm not really sure how to navigate them.
Here are the errors:
Notice: Undefined index: past in /messages.php on line 6
-- This makes sense, I think. I haven't built the client side yet, so there should be no past variable provided.
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in /messages.php on line 16
--So, my background is client side, so what this tells me is that my $result variable has a boolean stored in it, instead of whatever is supposed to be in it for the mysql_fetch_assoc() function call. Since the else statement should trigger, that means that either mysql_query() is not working how properly, or my parameter for it is incorrect. I don't know which (if either), nor do I know the solution to either.
Warning: mysql_free_result() expects parameter 1 to be resource,
boolean given in /messages.php on line 24
--Again, same as above; semi-makes sense, very unsure how to go about fixing it.
So, after the errors, nothing is displayed below. Which makes sense because the conditions are written under the assumption they'll have a resource in it, not a boolean (I think??)
In my php file, if you compare it with the tutorial you'll see I took out the htmlentities() calls because I read on StackOverflow that they are not needed, and they didn't change the state of the errors I was getting either way.
Anyway, thanks so much for any advice/help given!
Here is my code so far:
chat.sql:
DROP TABLE IF EXISTS chatitems;
CREATE TABLE chatitems (
id BIGINT NOT NULL PRIMARY KEY auto_increment,
added TIMESTAMP NOT NULL,
user VARCHAR(64) NOT NULL,
message VARCHAR(255) NOT NULL
);
messages.php:
<?php
ini_set('display_errors','1');
//header( 'Content-type: text/xml' );
mysql_connect( 'localhost:/private/var/mysql/mysql.sock', 'root', '' );
mysql_select_db( 'http://localhost/Documents/JoistChat/chat.sql' );
if ( $_REQUEST['past'] ) {
$result = mysql_query('SELECT * FROM chatitems WHERE id > '.
mysql_real_escape_string( $_REQUEST['past'] ).
' ORDER BY added LIMIT 50');
} else {
$result = mysql_query('SELECT * FROM chatitems ORDER BY added LIMIT 50' );
}
?>
<chat>
<?php
while ($row = mysql_fetch_assoc($result)) {
?>
<message added="<?php echo( $row['added'] ) ?>" id="<?php echo( $row['id'] ) ?>">
<user><?php echo( $row['user'] ) ?></user>
<text><?php echo( $row['message'])?></text>
</message>
<?php
}
mysql_free_result($result);
?>
</chat>
test.html:
<html>
<head>
<title>Chat Message Test Form</title>
</head>
<body>
<form action="http://localhost/JoistChat/messages.php"
method="POST">
User: <input name="user" /><br />
Message: <input name="message" /><br />
<input type="submit" />
</form>
</body>
</html>
$past = '';
if ( !empty($_REQUEST['past']) ) {
$past = 'WHERE id > '.intval($_REQUEST['past']);
}
$sql = 'SELECT * FROM chatitems $past ORDER BY added LIMIT 50'
$result = mysql_query($sql) or trigger_error(mysql_error()." [$sql]");
You need to learn basic coding culture. Basic guidelines are
Do no repeat yourself. You are writing all the stuff twice
Always check for error
Do not stack too much code in one line. Make your code distinct, step by step. Need a program to create an SQL query? Okay. get the product of this code in a variable and pass it over. Do not fold all the program in a single line.
Format your SQL properly
This way you'll always know the reason of the problem and have your code run smooth and easier to maintain.
Also just noted that your way of selecting a database is quite a... strange. 'chat.sql' is a file with table creation code, not database. You have to create a database first, then create a table in it, then select newly created database.
As you have been told already, mysql ext is obsoleted. You have to use use PDO instead, as it's the only choice for PHP users whose only idea of database interaction is direct calls to API.
First, create a file with connection options, pdo.php
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
Then make your code this way
<?php
ini_set('display_errors','1');
//header( 'Content-type: text/xml' );
include 'pdo.php';
$past = '';
$bind = array();
if ( !empty($_REQUEST['past']) ) {
$past = 'WHERE id > ?';
$bind = array($_REQUEST['past']);
}
$sql = 'SELECT * FROM chatitems $past ORDER BY added LIMIT 50'
$stm = $pdo->prepare($sql);
$stm->execute($bind);
$data = $stm->fetchAll();
?>
<chat>
<?php foreach ($data as $row) { ?>
Since the 'past' index is not set, the boolean condition in the if-statement evaluates to false. As a result the else part is executed.
Your error messages tell you that the query
SELECT * FROM chatitems ORDER BY added LIMIT 50
resulted in a SQL error. Try running that query in your MySql client directly to see what the error is. My guess is that the table/database you are accessing is not created/selected.
I have an admission form which is getting value from database table. Scenario is I have list of courses a student select a course and I pass course ID in URL then use this code to get corresponding Course name in the field: (The form is designed in joomla using breezing forms.)
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
global $database, $rec;
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND name = 'CourseName'");
$row = $database->loadObjectList();
$rec = $row[0];
ff_setValue('ProsCourse', $rec->value);
Unfortunately I get this error:
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 7
Last known pos : Before form custom piece code at line 1
Error message : Undefined offset: 0
* EXCEPTION CAUGHT BY FACILEFORMS *
PHP error level : E_NOTICE
PHP filename : /home/web10385/public_html/**/components/com_breezingforms/facileforms.process.php(1219) : eval()'d code
PHP linenumber : 8
Last known pos : Before form custom piece code at line 1
Error message : Trying to get property of non-object
The above code is the before form piece.
Thanks
You are not constructing the database object....
You have declared $database but you haven't initialized it with an object...That's the problem..It seems you have forgotten it.
Since, before initializing it, it's a non-object type. And you have tried to use it two times, hence you got two errors.
global $database, $rec;
^^ uninitialized....
$database->setQuery("SELECT * FROM course_list WHERE record = '$course_id' AND
^^ but you are using it here....
$row = $database->loadObjectList(.....
^^ here....
From the information seen this is what may be the solution:
EDIT:
$database=JFactory::getDbo();
Here's what I have done:
In Form pieces > Before form add this script:
$this->execPieceByName('ff_InitLib');
$course_id= JRequest::getVar('CID');
//intialize BF utilities
$this->execPieceByName('ff_InitUtilities');
global $database, $rec;
$database = ff_select('SELECT * FROM course_list WHERE record = '.$course_id.' ');
$rec = $database[0];
Then add this to the VALUE field of the TEXT field (course name):
<?php global $rec; return $rec->name; ?>
That should do it.
Peace.