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!
Related
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?
I need to save the data from android into an online SQL database. I made a PHP file for doing the task. I am trying to save the data using GET in a PHP file but it always returns false. Kindly have a look at my code and please help. The file is called using an android application. Tried testing though REST add-ons for browsers.
EDIT : Problem - When I send the data using HTTP GET all I get in return is the JSON result {"result":false}. This means my SQL query does not run properly. I tried running the same code directly in phpMyAdmin and it works.
EDIT : Code corrected.
<?php
$con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");
$rrequest_status = $_GET['request_status'];
$rstudent_name = $_GET['student_name'];
$rrequest_to = $_GET['request_to'];
$renrollment_no = $_GET['enrollment_no'];
$rout_date = $_GET['out_date'];
$rout_time = $_GET['out_time'];
$rin_date = $_GET['in_date'];
$rin_time = $_GET['in_time'];
$rrequest_time = $_GET['request_time'];
$rapproved_time = $_GET['approved_time'];
$rvisit_place = $_GET['visit_place'];
$rvisit_type = $_GET['visit_type'];
$rcontact_number = $_GET['contact_number'];
$squery = "INSERT INTO `gatepass_requests` (
`gatepass_number` ,
`request_status` ,
`student_name` ,
`request_to` ,
`enrollment_no` ,
`out_date` ,
`out_time` ,
`in_date` ,
`in_time` ,
`request_time` ,
`approved_time` ,
`approved_by` ,
`visit_place` ,
`visit_type` ,
`contact_number`
)
VALUES (
NULL ,
'".$rrequest_status."',
'".$rstudent_name."',
'".$rrequest_to."',
'".$renrollment_no."',
'".$rout_date."',
'".$rout_time."',
'".$rin_date."',
'".$rin_time."',
'".$rrequest_time."',
NULL,
'".$rapproved_by."',
'".$rvisit_place."',
'".$rvisit_type."',
'".$rcontact_number."',
)";
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
echo json_encode($result);
mysqli_close($con);
?>
To set the record straight for future readers.
The fact of the matter here is that you have different/undefined variables for the following used in your VALUES:
$rrequest_status
$rrequest_to
$rrequest_time
But have declared them as, and with an extra "r" and assuming that is your real code and not just a bad paste in your question:
Sidenote: Assuming the GET requests as opposed to POST.
$request_status = $_GET['request_status'];
$request_to = $_GET['request_to'];
$request_time = $_GET['request_time'];
And error reporting would have have signaled undefined variables notices but failed to mention that.
http://php.net/manual/en/function.error-reporting.php
Then you stated this comment in an answer given:
"Thank You so much for your reply, I removed it for the time being, but it is not the problem. PHP does allow to have trailing commas so it doesn't matter. – Pradumn Kumar Mahanta"
Maybe for certain PHP operations, but we're dealing with MySQL here and that alone would have thrown you an exception about the trailing comma for:
'".$rcontact_number."', <<<
In regards to the SQL injection you're open to, use a prepared statement:
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php (MySQLi_)
http://php.net/pdo.prepared-statements (PDO)
Error checking references:
http://php.net/manual/en/function.error-reporting.php (PHP)
http://php.net/manual/en/mysqli.error.php (MySQLi)
As you used $con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");. So you are following Object oriented style. So, you need to follow Object oriented style for executing query. Right now you mixed Object oriented style & Procedural style
Change
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
To
if($con->query($squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
For more info, please have a look here Object Oriented Style & Procedural Style
Remove extra , from the insert query.
'".$rcontact_number."', <-- this one
To check what error comes, do following:
if(mysqli_query($con,$squery)) {
$result['result'] = true;
} else {
$result['result'] = mysqli_error($con); // instead of false, use mysqli_error($con)
}
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.
I had someone build out a custom CMS for a small site and now I can't get a hold of the developer. I get this error when trying to view my site:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near 'order by sortorder' at line 1:
select path, title
from pages
where parent_id =
order by sortorder
After some help I was able to I think pin point where the problem is:
public function getChildLinks()
{
$list = array();
$WHERE_path = substr($_SERVER['REQUEST_URI'], 1);
$WHERE_path = strlen($WHERE_path) ? '= "'.$WHERE_path.'"' : 'IS NULL';
$parentPageRowset = Axl_Db::query('SELECT id, parent_id FROM '.$this->_name.' WHERE path '.$WHERE_path);
$parent_id = $parentPageRowset[0]['parent_id'] ? $parentPageRowset[0]['parent_id'] : $parentPageRowset[0]['id'];
$listRowset = new Axl_Db_Rowset('SELECT path, title FROM '.$this->_name.' WHERE parent_id = '.$parent_id.' ORDER BY sortorder');
while($listRowset->next())
{
$list['/'.$listRowset->path] = $listRowset->title;
}
return $list;
}
This is the function causing the problem.
The issue is with your WHERE clause; it has parent_id = but nothing following. You need to provide a value into the query.
More than likely the CMS needs a GET var in the url in order for the mysql statement to work.
Well after getting great feed back from Adam I was able to really pin point what file I needed to fix and or look into a little deeper.
It turns out that I needed to quote out the parent_id variable
like so:
$listRowset = new Axl_Db_Rowset('select path, title from '.$this->_name.' where parent_id = "'.$parent_id.'" order by sortorder');
Thanks Adam for your help
Drupal version 6.12
I have a page whose input format is PHP.
I simply want to update a database table. The SQL code appears to be too complex for db_query. I can not make db_query work nor does including php nor does dropping custom php code into the “Body” seem to work either. Any advise on how I can make the following code work inside Drupal?
Here is the code we put in the body. I tried creating a PHP file and just including the PHP file with an INCLUDE statement too.
I know the PHP is error free. it was taken from a site that does not use Drupal!
<?php
if( isset( $_GET['file'] ) )
{
$fileno = $_GET['file'];
$client = $_POST["Client"];
$DBLink = pg_connect("host=XXXX dbname=XXXX user=XXX password=XXXX" );
$sql = "update
webform_submitted_data sd set data = 'A'
where
sd.nid = '27' and
sd.cid = (select wc.cid from webform_component wc where wc.nid = sd.nid and wc.form_key = 'status') and
sd.sid = (select wd.sid from webform_submitted_data wd, webform_component wc
where wc.nid = sd.nid and wc.form_key = 'your_file_' and wd.nid = wc.nid and
wd.data = '$fileno');"
if( ! pg_query($DBLink, $sql) )
{
print( "Database Connection Failure: " . pg_last_error($DBLink));
exit;
}
else
{
print "File: $fileno is now Assigned to $client";
}
pg_close($DBLink);
}
?>
I also tried calling the Drupal APIs for sending an update to the database with no luck either, see code that follows. I actually tried this method first before giving up and trying the code above.
I also tried two versions of the db_query. The one you see below and one where I replaced %s with $fileno in the $sql string and called db_query($sql).
<?php
if( isset( $_GET['file'] ) )
{
$fileno = $_GET['file'];
$client = $_POST["Client"];
$sql = "update
webform_submitted_data sd set data = 'A'
where
sd.nid = '27' and
sd.cid = (select wc.cid from webform_component wc where wc.nid = sd.nid and wc.form_key = 'status') and
sd.sid = (select wd.sid from webform_submitted_data wd, webform_component wc
where wc.nid = sd.nid and wc.form_key = 'your_file_' and wd.nid = wc.nid and
wd.data = '%s');"
db_query($sql, $fileno);
print "File: $fileno is now Assigned to $client";
}
?>
I also put my database in full logging mode, logging connections and all statements and neither query hits the database. In the first case, if I INCLUDE the PHP I get just a white/blank screen -- it's like the PHP code is running but drupal is parsing the code before running it. I just want the code to run AS-IS.
Also, I'm really not interested in creating drupal modules. If it's possible to make this work without a lot of Drupal customizattion, that's what I'm after. This is a short-term tactical fix while we work on a more strategic goal...
Thanks all!
A couple of questions and thoughts:
Are there any database errors that appear on the screen? They usually appear in red 'warning' message boxes at the top of the content after an error has occurred.
Instead of webform_component you should be using {webform_component}. All table names should be in brackets.
The proper way to use data from a form input is to use $form_values[] for a form or $node for a node (if the data is part of a node). Additionally, if you are using the webform module, you can add steps to the submission of a webform. There are some tutorials here.
Last, does php actually reach the if if( isset( $_GET['file'] ) )? Drupal will complain heavily about database errors. So if you don't receive an error message, it means that the query was not executed (never got to that step) or it executed cleanly (but perhaps not with the intended effect).
In my experience, there haven't been queries that have been too complex for drupal because you are entering SQL (sanitized and parametrized) directly.