I have a problem in my code that maybe someone can check and point out the problem. I'm creating two webpages in php and I'm requesting variables from one page to another. As you see in the photo in my first page I have a drop list of values I successfully grab from a database. In the second page I want to print a list of matching items which are boats based on the choice the user select from the first page. Now from there I creating a sql query to first check that the user is not selected 'All' or not mixing 'All' with the provided choices. If either is not the case then the database field name is equal to the requested item and echo that to the screen. In second page I have successfully connected to the database. The problem is when testing my code, the screen is blank which means, my string is faulty. Thanks in advance. Here is my code
From what I can see here you're continuously overwriting the value of sqlStr instead of adding to it.
And you're missing $ before sqlStr
Try:
$sqlStr = "SELECT * FROM boats Where";
if($boatClass == 'All')
(
$sqlStr .= " AND 1=1";
)
else
{
'Class' = $boatClass;
}
if($boatMake == 'All')
(
$sqlStr .= " AND 1=1";
)
else
{
'Make' = $boatMake;
}
if($Year == 'All')
(
$sqlStr .= " AND 1=1";
)
else
{
'Year' = $Year;
}
if($used == 'All')
(
$sqlStr .= " AND 1=1";
)
else
{
'UsedOrNew' = $used;
}
A blank page means you have parsing errors. If you are working on a dev machine only, you can change the php.ini to display errors. By default it is off for security reasons.
Or you can check the error log, it gets populated every time a script with errors in it is run.
To find where your log file is, run a phpinfo script: http://php.net/manual/pt_BR/function.phpinfo.php and check for error_log.
If it is blank, then default locations for error log file:
linux + nginx is: /var/log/nginx/error.log
linux + apache is: /var/log/apache/error.log
Windows is likely to be in path/to/php/log/error-something.txt
Hope this helps,
Related
Anyone who can help on how to apply MariaDB: IF-THEN-ELSE Statement in PHP.
I want to query when the account type is Admin and he/she created the data in pre_registered table the Cancelled status also display in the list but if he/she is Admin but not the on who created the data it will not display on the list. If normal user is logged in the system, the Cancelled status will not be included in the list.
I have try the below query but did not work.
<?php
$account_type = getActiveAccountType($connect);
$query = "SELECT * FROM pre_registered WHERE ";
if ($account_type == 'Admin') {
$query .= "
IF registered_created_by != ".$_SESSION['account_id']." THEN
{
registered_status != 'Cancelled'
}
END IF;
";
} else if ($account_type == 'User') {
$query .= "
registered_status != 'Cancelled'
";
}
You want registered_status != 'Cancelled' in regardless of the user type, so include this in $query.
For the admin user, you want to include results with registered_created_by = $account_id. So in this PHP if branch. Because its an OR condition, it will be included regardless of the registered_status.
$query .= ' OR registered_created_by = ?'
When executing this query as a prepared query, pass $_SESSION['account_id'] as the value to be used in the query.
I am new to programming as well, but I hope this helps.
Try getting the results first and write a condition that checks if registered_created_by == $_SESSION['account_id'], then show the column if it does and hide if it doesnt.
I have a legacy PHP script which creates a list of resources from information stored in a MySQL database. Users can search the list or filter by the first letter in the title (this is stored as a column in the database). You can see it in action here: http://lib.skidmore.edu/library/index.php/researchdatabases). The script works fine except for one resource, FT.com, which appears incorrectly when users filter by letter. Regardless of the letter selected, its entry will be either at the top or the bottom. Note that in the unfiltered view FT.com is in proper alphabetical order. My first thought was to look at the database entry, but everything looks fine.
My hypothesis is a variable is not being set correctly. The way the script works is the top half of it contains a web form. The PHP below then picks up the input and assigns it to the variable $searchletter.
A combination of while loops and mysqli queries then retrieves and displays the results. Interestingly when the $searchletter = !empty line is commented out, the entire list disappears for the unfiltered view except for the FT.com entry (see this test script for an example: http://lib.skidmore.edu/library/search_dbs2.php). Otherwise I can see anything in neither the script nor the database which might be causing the observed behavior. Is my suspicion correct?
Here is the code. I've included everything except the connection information so you can see how it all works.
$search=(isset($_GET['search']) ? $_GET['search'] : null);
$search = !empty($_GET['search']) ? $_GET['search'] : 'default';
$search= addslashes($search);
$searchletter=(isset($_GET['searchletter']) ? $_GET['searchletter'] : null);
$searchletter = !empty($_GET['searchletter']) ? $_GET['searchletter'] : 'default';
var_dump ($_GET['searchletter']);
$con=mysqli_connect(DB_HOST,WEBMISC_USER,WEBMISC_PASS,DB_NAME);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($search == "default" && $searchletter == "default"){
$result = mysqli_query($con,"SELECT title,summary,url,coverage,format FROM dbs");
//This while loop creates the inital A to Z list.
while($row = mysqli_fetch_array($result))
{
$url=$row['url'];
$title=$row['title'];
$summary=$row['summary'];
$coverage=$row['coverage'];
$format=$row['format'];
echo <<<HTML
<p><h6>$title</h6>
<br />$summary</p>
HTML;
}
}
else {
$result = mysqli_query($con,"SELECT title,summary,url,coverage,format,fletter FROM dbs where title like '%$search%' or summary like '%$search%' or fletter = TRIM('$searchletter')");
//This block creates the filtered and searched version of the list.
while($row = mysqli_fetch_array($result))
{
$url=$row['url'];
$title=$row['title'];
$summary=$row['summary'];
$coverage=$row['coverage'];
$format=$row['format'];
echo <<<HTML
<p><h6>$title</h6>
<br />$summary</p>
HTML;
}
mysqli_close($con);
the first serious problem with this script is that it seems to be prone to MySQL Injection, the most serious problem of them all. (but I may be wrong). Please consider switching this code to PDO and its prepared statements and bindParam method.
the second is that, in the FORM you either support search OR letter (but not both)
BUT you use both in mysql query.
you should split the result fetching from
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where title like
'%$search%' or summary like '%$search%' or fletter = '$searchletter'");
into if/else statement:
if(!empty($search)){
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where title like
'%$search%' or summary like '%$search%'");
} elseif(!empty($searchletter)){
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where fletter = '$searchletter'");
}
this will not fire BOTH cases on the search and should return more reliable result based on your selection.
EDIT: after you added more code, it's clear that every "unset by user" field has value of "default". which means:
whatever letter you chose, the "seachphrase" will be set to "default" and "default" appears to be a part of FT.com summary field (you can see this word in search results). Again: splitting the query into two cases will solve this, so "default" word is never used in the search query.
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.
The below code displays data from a table and then filters it depending on the results of two combo boxes. I am able to order the results by ID once the form is submitted, but not on initial load (where all are listed). I have tried $sql = "SELECT * FROM Places ORDER BY ID"; which works when the list loads but returns an error when the form is submitted. Hope that makes sense. Any ideas? Thanks!
// Default query
$sql = "SELECT * FROM Places";
// check if form was submitted
if (isset($_POST['area'])) {
$connector = 'where';
if ($_POST['area'] != 'All') {
$sql .= " where Area = '".$_POST['area']."' ORDER BY ID";
$connector = 'and';
}
if ($_POST['theme'] != 'All') {
$sql .= " $connector Theme = '".$_POST['theme']."' OR Theme2 = '".$_POST['theme']."'
ORDER BY ID";
}
}
Your ORDER BY ID clause must appear at the very end of your statement. If both $_POST['area'] and $_POST['theme'] are filled, you end up with a query like this:
SELECT ... WHERE Area = 'some area' ORDER BY ID AND Theme = 'some theme'
Add the ORDER BY bit as the last part of your query.
I think you are missing a default behavior statement. I.e. Your IF statement doesn't have an else clause. So you are checking for isset and if it is change the select query, but there is nothing to say IF ! isset SELECT query should be .... ORDER BY ID.
Also I would try echoing your SQL queries out each time you set / change a portion of it to understand exactly what is being sent to the DB.
Lastly I always check the mysql.general_log table for the last run queries to see what is actually happening at the DB end.
It looks like it is possible for $_POST['area'] != 'All' and $_POST['theme'] != 'All'. In that case you will be putting the ORDER BY clause in twice. That probably your problem.
So try this.
// Default query
$sql = "SELECT * FROM Places";
// check if form was submitted
if (isset($_POST['area'])) {
$connector = 'where';
if ($_POST['area'] != 'All') {
$sql .= " where Area = '".$_POST['area']."'";
$connector = 'and';
}
if ($_POST['theme'] != 'All') {
$sql .= " $connector Theme = '".$_POST['theme']."' OR Theme2 = '".$_POST['theme'] . "'";
}
if ( $_POST['area'] != 'All' || $_POST['theme'] != 'All' ) {
$sql .= ' ORDER BY ID';
}
}
Thanks for all your help, I have solved the problem at the server end anyway so no need for code. Thanks for bringing attention to the security issues, I had these in the back of my mind but wasn't sure how bad it was! If I change the code to PDO would it help greatly? I have already reduced the privileges of the user to minimal. Thanks again.
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.