Hi, use the coalesce()
function:
select id, coalesce(c1, 0) + coalesce(c2, 0) + coalesce(c3, 0) ...
In practice, if the value of cN
is null it will output 0
.
Docs:
Bye!
Hi, use the coalesce()
function:
select id, coalesce(c1, 0) + coalesce(c2, 0) + coalesce(c3, 0) ...
In practice, if the value of cN
is null it will output 0
.
Docs:
Bye!
You are missing the dot after echo "Name:"
, the same happens for each line. So starting from the top, the first should be:
echo "Name: " . $xml->name . "\n";
Also, by enabling the error reporting at the top of the file:
error_reporting(E_ALL);
ini_set("display_errors", 1);
You should be able to see the error that explains the problem:
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in pet.php on line 8
Docs:
Bye!
That is good to make sure there is no double extension, but I can still include javascript in the file, for example I create a text file and save it as a.pdf with this contents:
<script>alert('hello');</script>
Then I upload it and this is what is received by the server:
File name is: a.pdf
Array
(
[pdf_main] => Array
(
[name] => a.pdf
[type] => application/pdf
[tmp_name] => /tmp/phpNrA2Xg
[error] => 0
[size] => 25
)
)
Now, as you see the mime type is completely wrong as this is a text file, and if you open the file from the server the script will be executed. In case of document files it's important to check the mime, in case of images it's important to check the mime and to strip the comment blocks, because those can be used as containers for PHP code.
So, you want to compare the string that you want to insert into table B against the values in table A, if they match then the insert should go fine, otherwise you want to insert the value into table C. Correct?
If I'm not wrong, a trigger cannot stop the insert statement, unless you use SIGNAL
with MySQL 5.5+, but this will cause an error.
You could use procedure instead of the insert & trigger events, so instead of:
insert into tableB (value) values('oranges');
it will be something like:
call matchAB('oranges');
And from there you decide where to insert the value.
That drop of Duncan Weir at the last minute still hurts here... but it was well deserved. I can already see the whitewash coming to us.
England and Ireland giving everything for the full 80 minutes
Beautiful game, indeed. Ireland and England performances are stellar right now.
Ok, I assume this is created by an SQL query:
$pacient[$val['pacientid']][] = $val['f_name']." ".$val['s_name'];
and that the pacientid
is the same for the surnames you want to compare, so this array will create a group of names like this:
Array
(
[1] => Array
(
[0] => anna lukaševica
[1] => anna lukashevicha
[2] => anna lukaševica
)
)
Correct? If yes, the check could be done at database level. Anyway, by changing your loop, maybe you can get the expected result:
<?php
$values = array(
array(
'pacientid' => 1,
'f_name' => 'anna',
's_name' => 'lukaševica',
),
array(
'pacientid' => 1,
'f_name' => 'anna',
's_name' => 'lukashevicha',
),
array(
'pacientid' => 1,
'f_name' => 'anna',
's_name' => 'lukaševica',
),
);
$pacient = array();
foreach($values as $key => $val)
{
$pacient[$val['pacientid']][] = $val['f_name']." ".$val['s_name'];
}
$result = array();
foreach($pacient as $pac)
{
$result[] = array_unique($pac);
}
print_r($result);
Will output:
Array
(
[0] => Array
(
[0] => anna lukaševica
[1] => anna lukashevicha
)
)
if you're processing only one pacientid
per time, then you do not need the extra array given by $result
:
$result = '';
foreach($pacient as $pac)
{
$result = array_unique($pac);
}
And you get:
Array
(
[0] => anna lukaševica
[1] => anna lukashevicha
)
At this point you can count the elements in the array; having more than one result will be the same of performing if(string1 != string2)
, so:
if(count($result) > 1)
{
//register the surname variation
}
…Hi!
Try to print the mime type received by the $_FILES
array. Sometimes the .doc
files are not correctly detected. So try:
print_r($_FILES['pdf_main']['type']);
You can also use the Finfo library to check the mime:
$mimes = array(
'application/msword',
'application/pdf'
);
$finfo = new Finfo(FILEINFO_MIME_TYPE);
if( ! empty($_FILES['pdf_main']['name']) && ! in_array($finfo->file($_FILES['pdf_main']['type']), $mimes))
{
# error
}
Important: check with different browsers, because the mime type is sent to the $_FILES
array from the client, so if the detection is wrong (or altered) on the client side, you will get an unexpected result. For this reason the Finfo approach is safer: because you effectively check the mime type. In some cases neither this is completely safe. And consider using an antivirus against the doc files, since these can contain infected macros.
Docs:
Hi,
do you want to compare this:
array(2) {
[0]=>
string(16) "anna lukaševica"
[1]=>
string(17) "anna lukashevicha"
}
between themselves, i.e. array[0] != array[1]
, or against the other resulting arrays? And once you get a match, which result you want to achieve? Also, by showing how you generate this array, maybe we can suggest a better approach.
Hi,
please can you explain better the relations between these three tables and the conditions that you want to use to insert the data? Right now I do not understand much.
Please reply by post, not by vote.
Do browsers cache scripts and emails?
If for script you refer to the PHP script generating the email then no, because PHP will output HTML to the client. When you send a mail, you cannot modify the code, you can only change the images remotely, but the Gmail change, makes this more difficult.
A part that, if you browse to Gmail and open the Chrome javascript console, you can check the headers sent to the browser: open a mail, select the Network tab, then reload the page.
You will see the elements received by the browser, click on XHR
and apply the filter rid=mail
, you will select two elements: one of these two (the text/html
type document) is the message container with HTML included.
Clicking on this element you open a window with these tabs:
Headers | Preview | Response | Cookies | Timing
if you click on Headers > Response Headers you will see that the Google server sends something like this:
alternate-protocol:443:quic
cache-control:no-cache, no-store, max-age=0, must-revalidate
content-encoding:gzip
content-length:3621
content-type:text/html; charset=UTF-8
date:Sat, 22 Feb 2014 18:19:31 GMT
expires:Fri, 01 Jan 1990 00:00:00 GMT
pragma:no-cache
server:GSE
status:200 OK
version:HTTP/1.1
As you see the directive is to not to cache. So this means, that if the browser acts correctly it will not save the email. You can verify it by typing in the URL bar the command about:cache
and then by searching (CTRL+F
) for rid=mail, you should not find any match. …
Yes, if you browse a page without session_start()
you cannot load the related data that you want to destroy.
Check the example: http://www.php.net/session_destroy
Hi,
maybe your problem is related to the recently privacy changes made by Gmail.
They are now caching HTML emails and so, the included images are not pulled directly from your server but from their proxy servers. It seems that only the first request can be tracked because they have to get the images from your server, then the images will be cached on their end for an amount of time and if two users receive the same image there will be only one request from your server, not two as expected so, right now, it seems that the subsequent openings cannot be tracked.
But if you create a dynamic tracking image, which differs for each user at each newsletter, then Google has to request it at least the first time, for everyone.
For more information check these links:
Not simple. Check out CMUSphinx and Julius projects:
Both are open source and provide a C API, Sphinx4 provides also a Java API. So if you want to make them work along with PHP you can create CGI scripts:
Or write a PHP extension:
You can do a test: load 500 files in a table database, then create a duplicate of this table without the blob field and perform some queries. MySQL provides a tool, the name is mysqlslap, that can give you some information about the performance of the queries:
I created a simple script that reads a directory and saves the images to a table imagedb
, if you want to try, below there is the code. Start from the table:
CREATE TABLE `imagedb` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`file` mediumblob NOT NULL,
`filename` char(32) NOT NULL,
`extension` varchar(5) NOT NULL,
`size` mediumint(8) unsigned NOT NULL DEFAULT '0',
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `filename` (`filename`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
The file
column will save the binary data. This is the script:
<?php
# database config
$dbconfig = array(
'hostname' => 'localhost',
'database' => 'dbname',
'username' => 'dbuser',
'password' => 'dbpass'
);
# config
$filespath = '/path/to/images'; // SET THIS
$exts = array('jpg', 'gif', 'png'); // allowed extensions
$listlimit = 500; // stop at 500 inserts
$sizelimit = 3500000; // soft limit at 3.5MB
if( ! is_dir($filespath)) exit('Directory does not exists!');
try
{
$pdo = new PDO("mysql:host=$dbconfig[hostname];dbname=$dbconfig[database]", $dbconfig['username'], $dbconfig['password']);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, TRUE);
$stmt = $pdo->prepare("INSERT IGNORE INTO imagedb (file, filename, extension, size, created_at, updated_at) values(:file, :filename, :ext, :size, :dt, :dt)");
# internal counters
$i = 0;
$e = 0;
$dir = dir(rtrim($filespath, '/') . '/'); …
Hi,
in this case you can use a subquery to return all the rows from user_status
: selecting their max(status_type)
and max(status_value)
and grouping by the user_id
. Then you need a row constructor:
select id, name from user, (select user_id, max(status_type) as status_type, max(status_value) as status_value from user_status group by user_id) as sub where id = sub.user_id and (status_type,status_value) != (10,11);
Live example: http://sqlfiddle.com/#!2/b1171/3
Documentation: http://dev.mysql.com/doc/refman/5.6/en/row-subqueries.html
Hi,
in my opinion, it is better to save the images in directories and the names in a database, mainly because you can serve the images as static content, without involving the PHP engine and the database in this output process.
Do you mean you want to select a specific row from a result set? Which API are you using: MySQLi, PDO, MySQL?
Hi, if you using this query in PHP then this value:
$_SESSION (['MM_Username'])
Must be:
{$_SESSION['MM_Username']}
Full query:
"SELECT transactions.UserName, transactions.transactionDate, transactions.transactionType, transactions.transactionAmount, transactions.OpeningBalance, transactions.EndBalance, users.FirstName, transactions.transactionID FROM transactions, users WHERE users.UserName = transactions.UserName AND users.UserName = {$_SESSION['MM_Username']} ORDER BY transactions.UserName, transactions.transactionID DESC"
Documentation:
What do I need to add or change so that any backups older than the 5 newest gets pruned?
In the local or in the backup server?
In addition: try to avoid the use of spaces in name constants, otherwise you have to use the constant()
function, I'm referring to these:
define( 'setq version-control t', 'YES' );
//Don't ask when deleting old backups
define( 'setq delete-old-versions t', 'YES' );
//Number of Numbered Backups to Keep
//Delete Oldest Version First
define( 'setq kept-old-versions' '5' );
define( 'setq kept-new-versions' '5' );
Also, it seems that the readConfig()
method reads the config file to populate an array, so, unless you have other reasons, you can avoid to define them as constants and match them through a regular expression. Instead, you can change the config file to an array, for example:
<?php
return array(
'KEEP_LOCAL_BACKUP_FILE' => 'YES',
'setq-version-control-t' => 'YES',
'setq-delete-old-versions-t' => 'YES',
'setq-kept-old-versions' => '5',
'setq-kept-new-versions' => '5',
'DO_REMOTE_FTP_COPY' => 'yes',
'CPANEL_SERVER_ADDRESS' => 'mywebsite.com',
'CPANEL_PORT_NUM' => '2082',
'CPANEL_ADMIN_USERNAME' => 'username',
'CPANEL_ADMIN_PASSWORD' => 'password',
'FTP_SERVER_ADDRESS' => 'remotewebsite.com',
'FTP_SERVER_PORT' => '21',
'FTP_USERNAME' => 'username',
'FTP_PASSWORD' => 'password',
'FTP_PATH_TO_COPY' => '/path/to/backupfolder/',
'FTP_USE_PASSIVE' => 'YES',
'FTP_USE_SSL' => 'NO'
);
And change your readConfig()
method to include the config file, for example:
public function readConfig()
{
$this->m_aConfig = include self::CONFIG_FILE;
return ;
}
Now, since the backup file names are based on a timestamp you can use a regular expression to match them and then use the diff()
method of the DateTime library …
Hi, before the undefined index notice there is:
unable to select dataid is empty
but this is no where in the above code, it could be related to the error. Also, do not mix backslash and slash as here:
c:\xampp\xampp\htdocs\rustoleum/photocms/
And if you want to use it, at least escape it, because the backslash is an escape character, so:
# escaped:
"c:\\xampp\\xampp\\htdocs\\rustoleum\\photocms\\"
# or with single quotes:
'c:\\xampp\\xampp\\htdocs\\rustoleum\\photocms\\'
# better with slashes:
'c:/xampp/xampp/htdocs/rustoleum/photocms/'
Docs:
PHP-Nuke 8.3.2 fix some security issues and become compatible with PHP 5.3.
By the way, this is not even completely true, most of their filters are based on the ereg functions, which are deprecated since 5.3 and vulnerable to the null byte attack. For example check their validate mail function at this link:
Now this is the test:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$email = $_GET['email'];
function validate_mail($email)
{
if(strlen($email) < 7 || !eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$", $email))
{
return 'E-mail error';
}
else
{
return $email;
}
}
echo validate_mail($email);
And submit a link like this:
http://localhost/example.php?email=your@email.com
It will print the mail, correctly, but try for example to add a second string, like another mail or a javascript:
# example 1
http://localhost/example.php?email=your@email.tld%00' or email='attacker@mail.tld'
# example 2
http://localhost/example.php?email=your@email.tld%00<script>alert('hello')</script>
If you add the null byte character %00
then: in the first case you can perform a SQL injection, in the second case you can perform an XSS attack. Now, in case of Google Chrome this code does not execute because of their CSP, and if you open the javascript console you will see why:
The XSS Auditor refused to execute a script in '... link ...' because its source code was found within the request. The auditor was enabled as the server sent neither an 'X-XSS-Protection' nor 'Content-Security-Policy' header.
but the other browsers will still execute the javascript.
More information:
Sorry for the update, I did a little error in my previous post, regarding the alternative to call the PHP executable. The correct version is this:
r = check_output(["/usr/bin/env", "php", "./reverse.php", "%s" % x.arg1])
Otherwise it will output an exception, I haven't noticed it before because I forgot to restart the server.
Yes, you can use the linefeed character \n
:
update table1 set color = concat_ws('\n', color, 'lime') where id = XX;
But from a usable point of view, a comma separated list is easier to manipulate, for example in PHP with explode()
to get an array or with str_replace()
to get a string:
print_r(explode(',' $row['color']);
echo str_replace(',', '<br />', $row['color']);
And you can also use the FIND_IN_SET()
function of MySQL:
Consider also JorgeM post, which is a far more flexible solution. Bye!
The correct solution would be to serve web.py as fastcgi together with PHP and ASP, this should be managed by a server as Apache or Nginx. But if you want to try the built in server you could do something like this:
#!/usr/bin/env python
import web
from subprocess import check_output
urls = (
'/', 'index',
'/reverse', 'reverse'
)
class index:
def GET(self):
return "Hello, world!"
class reverse:
def GET(self):
x = web.input(arg1='')
r = check_output(["./reverse.php", "%s" % x.arg1])
return "Reverse of " + x.arg1 + " is " + r
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
Then as PHP script:
#!/usr/bin/env php
<?php
echo strrev($argv[1]);
Make the php script executable:
chmod 755 reverse.php
Otherwise change this line:
r = check_output(["./reverse.php", "%s" % x.arg1])
With:
r = check_output(["/usr/bin/env php reverse.php", "%s" % x.arg1])
And then try the url:
http://localhost/reverse?arg1=hello
It should output olleh
. Note mine is just a test, this is not good for production usage.
Docs:
Please provide your code, otherwise it is difficult to help.
Hi!
You can use concat_ws()
to add content to a string, for example:
update table1 set color = concat_ws(',', color, 'green') where id = XX;
Full example:
> create table table1 (
id int unsigned auto_increment primary key not null,
color varchar(255) not null,
food varchar(255) not null);
> insert into table1 (id, color, food) values(1, 'red,green','rice');
> select * from table1;
+----+-----------+------+
| id | color | food |
+----+-----------+------+
| 1 | red,green | rice |
+----+-----------+------+
1 row in set (0.00 sec)
> update table1 set color = concat_ws(',', color, 'blue') where id = 1;
> select * from table1;
+----+----------------+------+
| id | color | food |
+----+----------------+------+
| 1 | red,green,blue | rice |
+----+----------------+------+
1 row in set (0.00 sec)
Regarding the insert query, this can support a subquery in which you can create the conditional statements, but in this case this is not the correct solution to update an existing value, because it will always add a new row, for example:
> insert into table1 (color) select concat_ws(',', color, 'orange') as color from table1 where id = 1;
> select * from table1;
+----+-----------------------+------+
| id | color | food |
+----+-----------------------+------+
| 1 | red,green,blue | rice |
| 2 | red,green,blue,orange | |
+----+-----------------------+------+
2 rows in set (0.00 sec)
And since the id
column is a primary key, if you remove the auto_increment
it will still produce an error for duplicate key.
The alternative …
@arslanqamar thank you for your attention! I see what you meant:
header("Content-Disposition:attachment;filename=$zipname");
And you are precisely correct. I chose to use random_name.zip
instead of the $zipname
value, to evidence that the name of the file can be an arbitrary value. In some cases this, together with a restricted path, can be useful to avoid direct linking to the original file.
Look at the ZipArchive class:
An example:
<?php
# array of files
$files = array(
'feh.jpg',
'img1.jpg'
);
# name
$zipname = 'archive.zip';
# create the archive
$zip = new ZipArchive;
$res = $zip->open($zipname, ZipArchive::CREATE);
if($res === TRUE)
{
foreach($files as $file)
{
$zip->addFile($file);
}
$zip->close();
}
# send to download
header('Content-type:application/zip');
header("Content-Disposition:attachment;filename='random_name.zip'");
readfile($zipname);
But if you can separate, these tasks, zip the archives in a background process and save them for a while, so that the server does not have to perform the same action multiple times.
You can create the array of files through the glob()
function, a form, a database, this is up to you.
Docs: http://www.php.net/glob
Hi,
you could explode by the spaces between the names:
$names = explode(' ', $row['name']);
echo $names[0];
echo $names[1];
BUT you cannot distinguish between name, middlename and lastname. The correct solution would be to normalize this information during the collection step. Which means:
firstname: <input type="text" name="firstname" /><br />
middlename: <input type="text" name="middlename" /><br />
lastname: <input type="text" name="lastname" /><br />
And then insert it in the appropriated columns:
insert into users (firstname, middlename, lastname) values($fname, $mname, $lname);
More information here:
I've used this a couple of times:
Hi,
I think the OP wants to check if a given image matches the minimum print sizes at a defined DPI:
<?php
$image = 'img1.jpg';
list($w, $h) = getimagesize($image);
$dpi = 150;
# current sizes in inches
$inW = round($w / $dpi, 2);
$inH = round($h / $dpi, 2);
# min print sizes in inches
$printW = 5;
$printH = 5;
echo PHP_EOL;
if($inW >= $printW && $inH >= $printH)
{
echo "Correct, the print sizes at {$dpi}DPI are: {$inW} x {$inH} inches";
}
else
{
echo "This image is too small";
}
echo PHP_EOL;
With an image at 1920x1080
the result will be 12.8x7.2
inches. You can get the same result with ImageMagick, as suggested by Pritaeas, for example from the command line:
identify -format "%[fx:w/150] by %[fx:h/150] inches" img1.jpg
If the undefined index message is related to the $_POST
variables it is because when you normally open a page you execute a GET request, when you submit the form, instead, you perform a POST request and only in this case the $_POST
array is populated.
So from:
$name = $_POST['name'];
You will get:
Notice: Undefined index: name ...
In order to stop this you can place an IF
statement checking if the $_POST
array is true:
if($_POST)
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Demo';
$to = 'info@domain.com';
$subject = 'Hello';
$human = $_POST['human'];
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
}
The first argument of the anchor()
function can accept an array or a string, so:
$segments = array(
'product',
'id',
'1',
'?version=12&name=mydoc'
);
# with array
echo anchor($segments, 'click me');
# with string
echo anchor('/product/id/1?version=12&name=mydoc', 'click me');
the difference between the two is that the former will output a trailing slash after the $id
(with value 1) segment:
# version 1
http://localhost/product/id/1/?version=12&name=mydoc
While the latter no:
# version 2
http://daniweb.ci/product/id/1?version=12&name=mydoc
but, in both cases it should work fine, the point is to include the ?
in the segment.
If you want to generate only the second version of the links through an array, then this could be done by extending the url helper, for example by simply exploding the string at the ?
character and removing the right slash. In application/helpers
create the file MY_url_helper.php and paste this:
<?php
if ( ! function_exists('my_anchor'))
{
function my_anchor($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
# new edit
$querystring = explode('?', $site_url);
$querystring[0] = rtrim($querystring[0], '/');
$site_url = implode('?', $querystring);
# stop edit
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
}
Then from the view call the new function my_anchor()
as submit the same arguments of the anchor()
helper:
$segments …
I'm not sure I've understood but you can use both at the same time. For example you have a method like this one:
public function activation($id)
{
$data = array(
'id' => $id,
'code' => $this->input->get('code', true)
);
$this->load->view('signup/activation', $data);
}
And call the url in this format:
http://localhost/signup/activation/1?code=random_string_123
The important is to set to TRUE the allow_get_query
in the config file, so that the appended query string will be regularly processed:
$config['allow_get_array'] = TRUE;
Sure, timestapmdiff()
is a function of MySQL that returns the difference between two dates. By the way, there was an error in my previous example, the comparision operator is <=
not =<
.
This function takes 3 arguments: the first argument is the unit and can assume the value of: year
, quarter
, month
, week
, day
, hour
, minute
, second
, microsecond
. The other two arguments are the datetime expressions: these can be strings representing a timestamp or datetime column types. For example:
> select timestampdiff(hour, '2014-02-10 23:30', '2014-02-11 11:30') as difference;
+------------+
| difference |
+------------+
| 12 |
+------------+
1 row in set (0.00 sec)
As you see you get an integer, this can be signed i.e. it can be negative if you reverse the values, for example:
> select timestampdiff(hour, '2014-02-11 11:30', '2014-02-10 23:30') as difference;
+------------+
| difference |
+------------+
| -12 |
+------------+
1 row in set (0.00 sec)
In my previous post:
select id, title, date from article where timestampdiff(hour, date, now()) <= 10;
I used the date
column of your table as second argument and the now()
function as third argument and then the comparison operator <=
(less than or equal) to check the results and select only those matching the condition: less than or equal to 10
.
An example table:
create table article(
id int unsigned not null primary key auto_increment,
title varchar(200) not null,
date datetime not null
);
insert into article (title, date) values('data 1', '2014-02-09 18:00'); …
Hi,
if you're using MySQL then there is the timestampdiff()
function, for example:
select id, title, date from article where timestampdiff(hour, date, now()) =< 10;
Docs: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff
Or the DateTime library:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('d/m/Y h:i:s a');
Then you need something like this:
<?php
$url = 'domain.com';
$dnsquery = dns_get_record($url, DNS_SRV);
$records = array();
$match = '_autodiscover._tcp';
foreach($dnsquery as $key => $entry)
{
if(strstr($entry['target'], $match) !== FALSE)
{
$records[] = $entry;
}
}
print_r($records);
The $records
variable will return an array of entries that match the string. If it does not work try with DNS_ALL
.
You're welcome! I know, it requires more work and to be precise your script should be modified to use prepared statements, it will help to avoid SQL injections (but not always), something like this should work with PHP 5.2.1 and above:
$query = "SELECT SQL_CALC_FOUND_ROWS test_static_content.title, test_static_content.content, test_static_content.images from test_static_content WHERE upper(test_static_content.images) LIKE :find or upper(test_static_content.title) LIKE :find or upper(test_static_content.content) LIKE :find UNION ALL SELECT test_dynamic_content.title, test_dynamic_content.content, test_dynamic_content.images FROM test_dynamic_content WHERE upper(test_dynamic_content.images) LIKE :find or upper(test_dynamic_content.title) LIKE :find or upper(test_dynamic_content.content) LIKE :find";
And:
try
{
$find = '%'.$find.'%';
$pdoStatement = $pdo->prepare($query);
$pdoStatement->bindParam(':find', $find, PDO::PARAM_STR);
$pdoStatement->execute();
}
With previouses versions of PHP, instead you have to bind each parameter separately:
$pdoStatement->bindParam(':find1', $find, PDO::PARAM_STR);
$pdoStatement->bindParam(':find2', $find, PDO::PARAM_STR);
$pdoStatement->bindParam(':find3', $find, PDO::PARAM_STR);
...
And obviously match them in the prepared query.
@gabrielcastillo good suggestion, it could be done when the script receives the POST request, decode the input, filter and send back clean data, at that point there's no need to perform it in the textarea. For example:
<?php
if($_POST)
{
$filter['contents'] = htmlspecialchars_decode($_POST['contents']);
# clean the input
require './library/HTMLPurifier.includes.php';
require './library/HTMLPurifier.autoload.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
$config->set('HTML.Allowed', 'p,a[href|target],em,strong,div[align],br');
$config->set('Attr.AllowedFrameTargets', array('_blank'));
$purifier = new HTMLPurifier($config);
$data['contents'] = $purifier->purify($filter['contents']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>TinyMCE</title>
<script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea",
plugins: "code",
valid_elements : "a[href|target=_blank],strong,em,div[align],br"
});
</script>
</head>
<body>
<h2>Test</h2>
<form method="post">
<textarea name="contents"><?php echo array_key_exists('contents', $_POST) ? $data['contents']:''; ?></textarea>
<input type="submit" name="submit" value="send" />
</form>
<?php
if($_POST)
{
echo "<h3>POST:</h3><pre>";
highlight_string($data['contents']);
echo "</pre>";
}
?>
</body>
</html>
Uhm. I think I cannot help much more, I believe that all these differences happens because, in my case, PDO uses the MySQL Native Driver, while yours is probably using libmysqlclient:
You could try to fetch the results before performing the second query, so:
$result = $pdoStatement->fetchAll();
$countRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
if ($countRows == 0) {
And then the while loop would become a foreach loop:
foreach($result as $row => $column)
{
echo $column['title'];
echo $column['content'];
echo $column['images'];
}
But if it does not work wait for appropriate help.
You could use getmxrr()
:
<?php
$url = 'daniweb.com';
getmxrr($url, $matches, $weights);
print_r($matches);
print_r($weights);
Docs: http://php.net/getmxrr
Regarding dns_get_record()
what kind of problem do you experience? Can you show your script?
I need to be able to display the srv record below the textbox, the srv record needs to start with _autodiscover._tcp.
Do you mean you want to filter and get only those with _autodiscover._tcp.
? Here you can use strstr()
or preg_match()
or even preg_match_all()
if the record contains more then one matching string.
If you can use a plain-text it will be easier, because you can use the file()
function to read into an array each line of the file, then just loop it through preg_match()
to extract the postal codes. Now, if these are the UK postal codes there should be a rule to match only the valid combinations. Here's an example:
<?php
$source = file('source_uk.txt');
$result = array();
$i = 0;
$pattern = "/\b([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\ 0[Aa][Aa])|([Ss][Aa][Nn]\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\ {0,1}([Cc]\/[Oo]\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\ {0,1}1[Zz][Zz]))\b/";
foreach($source as $line)
{
$result[$i]['address'] = trim($line);
if(preg_match($pattern, $line, $match) == 1)
{
$result[$i]['postcode'] = trim($match[0]);
}
$i++;
}
print_r($result);
It will output:
Array
(
[0] => Array
(
[address] => Velta - The Underfloor Heating Company, Wombwell School, S73 8AX
[postcode] => S73 8AX
)
[1] => Array
(
[address] => Speedy Asset Services Limited, C/O Arnold Clark, CW9 5GG
[postcode] => CW9 5GG
)
[2] => Array
(
[address] => Owen Brown Limited, Metal & Wood Shop, DE74 2NL
[postcode] => DE74 2NL
)
[3] => Array
(
[address] => Getrag Ford Transmission, Britain, Off Speke Boulevard, L24 9LE
[postcode] => L24 9LE
)
[4] => Array
(
[address] => PDM Ltd, Stoke Lane, NG14 5HJ
[postcode] => NG14 5HJ
)
[5] => Array
(
[address] => Robert Kirkland (Blyth) Ltd, Belsay Close, NE61 6XG
[postcode] => NE61 6XG
)
[6] => Array
(
[address] => MCS Ltd, C/O Carillion Advanced Works Project, BS10 5NB
[postcode] => BS10 5NB
)
[7] => Array
(
[address] => MCS Ltd, …
Hi, by "word document" are you referring to Microsoft Word file? doc
or docx
? Or it is just a plain-text file?
Ok, something I wasn't considering: rowCount()
does not always return the numbers of rows of a select query, this works only for insert, update and delete queries.
From the docs:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
To get the total you have to run a secondary query, this can be run previously to the main to check the number of rows, otherwise you can use FOUND_ROWS()
after the execution of the query, MySQL will return the total. So in order to work with your script change line 73
:
if ($pdoStatement->rowCount() == 0) {
with:
$countRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
if ($countRows == 0) {
And line 102
:
$anymatches=$pdoStatement->rowCount();
with:
$anymatches = $countRows;
Note that FOUND_ROWS()
is available only on MySQL and forks, so if you decide to change database you will have to modify your script logic.
Reference:
In addition, you could use a PHP array, for example create fruits.php:
<?php
return array(
'red' => array(
'Cherries',
'Cranberries',
'Pomegranate',
),
'green' => array(
'Avocados',
'Cucumbers',
'Honeydew',
),
'blue' => array(
'Blueberries',
'Fig',
'Plums'
)
);
Then you can include it in your script as a configuration file:
<?php
$fruits = include 'fruits.php';
print_r($fruits['red']);
foreach($fruits['blue'] as $fruit)
{
echo $fruit;
}
With this structure you can create a multidimensional array with all the information about each Country and use it as you like. Bye!
Hmm, I'm not sure about this. By testing I see what you mean, but I also see that if I resubmit the same form, the allowed tags will be converted again:
<!DOCTYPE html>
<html>
<head>
<title>TinyMCE</title>
<script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea",
valid_elements : "a[href|target=_blank],strong,em,div[align],br"
});
</script>
</head>
<body>
<h2>Test</h2>
<form method="post">
<textarea name="contents"><?php echo array_key_exists('contents', $_POST) ? $_POST['contents']:''; ?></textarea>
<input type="submit" name="submit" value="send" />
</form>
<?php
if($_POST)
{
echo "<h3>POST:</h3><pre>";
highlight_string($_POST['contents']);
echo "</pre>";
}
?>
</body>
</html>
So the first time outputs:
<p>Hello <strong>World</strong></p>
The second time:
<p>Hello <strong>World</strong></p>
As expected. If instead you load the code plugin:
tinymce.init({
selector: "textarea",
plugins: "code",
valid_elements : "a[href|target=_blank],strong,em,div[align],br"
});
You can submit the code throught the Tools > Code tab and it won't be converted to entities. BUT if for example you submit quote
or another not whitelisted tag, it will be removed only after the resubmit, not during the first instance.
For now I stop here, hope it helps a bit to understand the problem. I think the best would be to find a method to disable completely this feature of TinyMCE and use HTMLPurifier or another similar library to clean the input.
So, have you tried to force it through the form? Since the charset of the tables is latin1 you should use iso-8859-1
instead of utf-8
:
<form name="contact" action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" accept-charset="iso-8859-1">
Otherwise you could convert the tables to utf8:
ALTER TABLE dynamic_content DEFAULT CHARACTER SET utf8;
ALTER TABLE static_content DEFAULT CHARACTER SET utf8;
I don't see anything else that could be wrong, in my test your script works fine.
Can you show the output of:
show create table dynamic_content;
show create table static_content;
It could be a problem of encoding, for example latin1 from your browser and utf8 in your tables, in this case you can force the form to submit the same encoding of the tables by adding the accept-charset
attribute, for example:
<form name="contact" action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" accept-charset="utf-8">