cereal 1,524 Nearly a Senior Poster Featured Poster

If there are not previous insert queries, then lastInsertId() will return 0, for this reason the loop does not run.

The MySQL documentation explains the reason:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

Link: https://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id

To get the last id you can do:

SELECT MAX(id) FROM tablename;

A consideration about the loop: if you delete one of the previous rows then you will get some errors, for example:

> select id from tablename;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
+----+

> delete from tablename where id = 2;

> select max(id) as last_id from tablename;
+---------+
| last_id |
+---------+
|       5 |
+---------+

The last id will always be 5, MySQL will not scale the values to occupy the missing row. As result, the loop will go through the id with value 2 even if it does not exists anymore. It's better to get the list of the …

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, can you show the query?

cereal 1,524 Nearly a Senior Poster Featured Poster

Once you get through the IF statement the new value, for the $level variable, will be valid for the remaining code:

$level = 0;
echo $level; # outputs: 0

# for the example, random choice
$a = rand(1, 2);

if($a == 1)
    $level = 1;

else
    $level = 2;

echo $level; # outputs: 1 or 2, nevermore 0
cereal 1,524 Nearly a Senior Poster Featured Poster

You're welcome!

cereal 1,524 Nearly a Senior Poster Featured Poster

I suppose you're using this plugin: http://jqueryvalidation.org/

If yes, then it seems you can define only one validation process for the chosen form, so don't set two of them:

$('#DemoForm').validate({
    rules:{},
    messages:{}
});

$('#DemoForm').validate({
    rules:{},
    messages:{}
});

Set only one for this ID. The second problem is given by the value assigned to the required attribute which needs to be boolean, not string. So, instead of:

required:"true",

Use:

required:true,

The same applies to the other attributes in which you define a boolean value, like email:

email:true,

Full example:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <title>jQuery Form Validation</title>
    </head>
    <body>

        <form method="post" action="jTest5.8.html" id="DemoForm" name="DemoForm">

            Username<br />
            <input type="text" id="user_input" name="username" /><br>

            Email<br />
            <input type="text" id="email" name="email" /><br>

            Password<br />
            <input type="password" class="form-control" name="password" id="password"/><br>

            Password Again<br />
            <input type="password" class="form-control" name="cfmPassword" id="cfmPassword" /><br>

            <input type="submit" value="submit"/>

        </form>

        <script src='jquery.validate.min.js'></script>    
        <script>
            $("#DemoForm").validate({
                rules: {
                    'email': {
                        required: true,
                        email: true,
                        },

                    'password': {
                        required: true,
                        minlength: 6,
                        maxlength: 10,
                        },

                    'cfmPassword': {
                        equalTo: "#password",
                        minlength: 6,
                        maxlength: 10
                        }
                    },

                messages: {
                    'email': {
                        required:'Please submit your email.',
                        email:'Enter a valid email.',
                        },
                    'password': {
                        required:"The password is required"
                        }
                    }
            });
        </script>

    </body>
</html>

Which should work fine.

mattyd commented: Thank you for all your help on this! +0
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

this is an intended behaviour of the browser, a website cannot define the file to upload from a client system, otherwise it could be used to steal anything. In any case, the browser works in a sandbox, so you cannot access directly to local resources.

cereal 1,524 Nearly a Senior Poster Featured Poster

It's fine, thank you Dani!

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, I think you have to fix the opening form tags, at the moment you have three of them, the first is not closed and it will lead to some errors:

<form id="DemoForm"

The second is well defined:

<form method = 'post' action = 'jTest1.8.html' id = 'DemoForm' name = 'DemoForm'>

The third is going to submit a GET request:

<form id="formCheckPassword">

Because the method is not defined and the default setting is to play GET.

When you submit the form, only the values of the third form will be submitted because these are contextual to the submit button, to include the input fields of the second form, you have to merge them into a single form:

<form method="post" action="jTest1.8.html" id="DemoForm" name="DemoForm">

    Username<br />
    <input type="text" id="user_input" name="username" /><br>

    Email<br />
    <input type="text" id="email" name="email" /><br>

    Password<br />
    <input type="password" class="form-control" name="password" id="password"/><br>

    Password Again<br />
    <input type="password" class="form-control" name="cfmPassword" id="cfmPassword" /><br>

    <input type="submit" value="submit"/>

</form>

Fix also the javascript validation rules, to match the same form ID, or simply merge them and you're finished.

mattyd commented: Thank you. I will work on this later and post the results here. +0
JorgeM commented: yep! +12
cereal 1,524 Nearly a Senior Poster Featured Poster

A POST request does not append any information to the url, it uses a separated request body, but it is possible to append GET variables to a POST request url. Are you using javascript to submit the form? Could you show the code?

cereal 1,524 Nearly a Senior Poster Featured Poster

It happens when you use the GET method, use POST instead.

mattyd commented: Thank you! +8
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi all!

I don't know if this occurs only to me but in the forum list view the read text icon wraps to a new line, like this:

read_gif.jpg

Here's a larger screenshot: http://i.imgur.com/k9w09hn.jpg

I noticed this few days ago. I don't have extensions on. I tested the zoom, but it doesn't change. I got the same results in Google Chrome and Mozilla Firefox:

  • Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
  • Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:37.0) Gecko/20100101 Firefox/37.0
  • Screen resolution: 1366x768
  • Browser window resolution: 1301x683
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

it is possible, read these articles:

but your question is a bit vague. If you offer more details, maybe we can suggest you better. Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi!

That's the format supported by the database, save it like this, then when your get the result set format as you prefer. You can do it directly at query level with the format_date() function:

or in PHP with the IntlDateFormatter class:

For this task I use a little class, that can can convert also to a more readable format and display the month name in the language you prefer. Here's the code:

<?php

    class Dtime extends IntlDateFormatter
    {
        private $date;

        public function __construct($datetime = '', $pattern = 'd MMMM yyyy HH:mm', $locale = 'it')
        {
            parent::__construct($locale, IntlDateFormatter::FULL, IntlDateFormatter::FULL);

            $this->date = new DateTime($datetime);
            parent::setPattern($pattern);
        }

        public function get()
        {
            return mb_convert_case(parent::format($this->date), MB_CASE_TITLE, "UTF-8");
        }
    }

By default the language is set to Italian, but this can changed, as the format, usage example:

$date = '2015-04-14 21:00';
$dt   = new Dtime($date, 'dd-MM-yyyy', 'it');
echo $dt->get();

Which returns 14-04-2015, the default setting:

$date = '2015-04-14 21:00';
$dt   = new Dtime($date);
echo $dt->get();

returns:

14 Aprile 2015 21:00

There are also other methods to format a date, you can use the DateTime class or the strtotime() function:

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

if I'm not wrong, this script is creating database tables and procedures, I suppose for MS SQL, so all you need is to convert them to queries that you would run in a database client. For example with the PDO API you can do:

try {

    # connect to the database
    $conn = new PDO("mssql:host=HOSTNAME;dbname=DATABASE", "USERNAME", "PASSWORD");

    # run queries
    $conn->query("SET ANSI_NULL ON");
    $conn->query("SET QUOTED_IDENTIFIER");
    $conn->query("SET ANSI_PADDING ON");
    $conn->query("CREATE TABLE `dbo`.`service`(`ser_id` int IDENTITY(1,1) NOT NULL, `ser_name` varchar(100) NULL, `ser_status` varchar(1) NULL, CONSTRAINT `PK_ison_service` PRIMARY KEY CLUSTERED (`ser_id` ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY) ON PRIMARY");
    $conn->query("SET ANSI_PADDING OFF");

} catch (PDOException $e) {
    die('Fail: ' . $e->getMessage());
}

In my example I'm using backticks to wrap the column names:

`test`

I'm not sure this is the correct syntax for MS SQL.

Note: the above example uses the PDO_DBLIB driver, but if you're on Windows and using PHP5.3+ you may have to load some modules and change the connection string according to the driver is use, as PDO_DBLIB is not anymore available, as alternatives you could use PDO_ODBC or PDO_SQLSRV. Here you can find some information:

If you can access the command line, consider also to create a simple SQL file and execute an import, something like:

exec("sqlcmd -S CONNECTION/STRING -i /path/to/FILE.sql");

Docs:

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, I got it, your code is perfect, the issue is in my logic.

By starting everything by zero I wasn't considering that when the $pages variable was divisible by $perpage (e.g. 100 / 10) the result would be 10, but the last range would be LIMIT 90, 10 at page 9, the issue happens because there is an extra query that sets the range LIMIT 100, 10 at page 10 and because the ELSEIF stop condition was current_page >= total_pages, which at the end translates to 10 >= 10 when, by starting from zero, it should have been 10 >= 9.

I was tricked by the $perpage set at three: the last page is 33 which generates LIMIT 99, 3 and returns only the last row which, in appearance, is correct.

It can be fixed to continue the script starting at zero, but at this point I think it is a better to start everything from one. I updated your last code, you can try it here:

And here's your code (updated):

<?php

    $servername = "localhost";
    $dbname     = "test";
    $dbusername = "root";
    $dbpassword = "";
    $error      = FALSE;
    $result     = FALSE;

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $total = $conn->query("SELECT COUNT(id) as rows FROM Posts")
                 ->fetch(PDO::FETCH_OBJ);

        $perpage = 3;
        $posts   = $total->rows;
        $pages   = ceil($posts / $perpage);

        # default
        $get_pages = isset($_GET['page']) ? $_GET['page'] : 1;

        $data = array(

            'options' => array(
                'default'   => 1,
                'min_range' => 1,
                'max_range' => $pages …
cereal 1,524 Nearly a Senior Poster Featured Poster

You're welcome! ;)

cereal 1,524 Nearly a Senior Poster Featured Poster

The query is still a problem, it is not correct to add an or die() statement to a query string that needs to be executed.

Regarding the IF condition fix the attribute name of the firstname input field in your form, at the moment there is an extra space, so change it from this:

<input type="text" id ="changefirstnamebox" name="firstname " maxlength="20">

To:

<input type="text" id ="changefirstnamebox" name="firstname" maxlength="20">

Otherwise you have to refer it as $_POST['firstname_'], the extra space is converted by PHP to an underscore.

cereal 1,524 Nearly a Senior Poster Featured Poster

A problem is this:

$sql ="UPDATE login SET firstname = '$newfirstname' WHERE  ID=$dbid" or die ("cant update " . mysqli_error($con));

Do only:

$sql = "UPDATE login SET firstname = '$newfirstname' WHERE ID=$dbid";

Otherwise mysqli_query() will return false.

cereal 1,524 Nearly a Senior Poster Featured Poster

Why you set $error = FALSE; and $result = FALSE; to False?

This is done to initialize the variables in my test script, otherwise if the database fails for some reason (no connection, query error) then PHP will show this notice:

Severity: Notice
Message: Undefined variable: result

by simply setting the variable $result = FALSE; PHP will run the code into the IF statements and will find other variables not initialized like $pages, $number, $next and $prev, also the loop at line 181 will fail. To avoid most of these errors I could do:

$pages  = FALSE;
$number = FALSE;
$next   = FALSE;
$prev   = FALSE;

But the loop warning will still remain:

Invalid argument supplied for foreach()

Why? Because of this:

$result = FALSE;
var_dump(count($result)); # int(1)

It returns 1, so the IF statement:

if(count($result) > 0)

Will fail, and it is not fixable by changing the condition to 1:

if(count($result) > 1)

because the query could return only one post. So to avoid the warning all you have to do is to verify if the variable is not FALSE. In my test script my check is implicit, this:

if($result)

Is equal to write:

if($result !== FALSE)

Note if you write:

if($result === TRUE)

The warning will disappear in case of database fails, but when the query works well it will not show any results because the types are different: $result will be an array and TRUE is …

cereal 1,524 Nearly a Senior Poster Featured Poster

No problem & happy holidays ;)

It can be done with MySQLi but you're mixing procedural and object oriented (OOP) styles.

In OOP the connection is open like this:

$db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

Then you can use $db to run the methods. MySQLi hasn't defined a fetch() method, in your case you would use fetch_object():

$row = $db->query('SELECT name FROM countries WHERE country_id = 15')->fetch_object();

echo $row->name;

Also: the query() method accepts a second argument, but this is used to define the result mode, here you can find some information about these modes:

For a list of fetch modes, instead, check the methods defined for the mysqli_result class:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hmm, no I don't think so. I wrote a test script, check if it works for you:

<?php

    $servername = "localhost";
    $dbname     = "mydbname";
    $dbusername = "mydbusername";
    $dbpassword = "mydbpassword";
    $error      = FALSE;
    $result     = FALSE;

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $total  = $conn->query("SELECT COUNT(id) as rows FROM Posts")
                  ->fetch(PDO::FETCH_OBJ);

        $perpage = 3;
        $posts   = $total->rows;
        $pages   = floor($posts / $perpage);

        # default
        $get_pages = isset($_GET['page']) ? $_GET['page'] : 0;

        $data = array(

            'options' => array(
                'default'   => 0,
                'min_range' => 0,
                'max_range' => $pages
                )
        );

        $number = trim($get_pages);
        $number = filter_var($number, FILTER_VALIDATE_INT, $data);
        $range  = $perpage * $number;

        $prev = $number - 1;
        $next = $number + 1;

        $stmt = $conn->prepare("SELECT ID, Author, Content FROM Posts LIMIT :limit, :perpage");
        $stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
        $stmt->bindParam(':limit', $range, PDO::PARAM_INT);
        $stmt->execute();

        $result = $stmt->fetchAll();

    } catch(PDOException $e) {
        $error = $e->getMessage();
    }

    $conn = null;
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>User View Page</title>
        <style type="text/css">

            body {
                font:1rem Arial,sans-serif;
                color:#1a1a1a;
            }

            a {
                text-decoration:none;
                color:#4281A4;
                transition: .3s color;
            }

            a:hover {
                color: #314CB6;
            }

            .error {
                width:100%;
                padding:.5em;
                background-color: #D7F75B;
            }

            .navigation span,
            .navigation a {
                display: inline-block;
                padding:0.5rem;
            }

            #wrap {
                margin:50px auto;
                width: 960px;
            }

            table {
                width:100%;
                border-collapse:collapse;
            }

            th {
                text-align:left;
            }

            tbody > tr:nth-child(odd) {
                background:#f3faf1;
            }

            tbody > tr:nth-child(even) {
                border-top: 1px solid #e5e5e5;
                border-bottom: 1px solid #e5e5e5;
            }

            td:first-child {
                width:25px;
            }

            td:nth-child(2) {
                width:10%;
            }

            thead th,
            tbody td {
                padding:.5rem;
                line-height:1.4rem;
            }

        </style> …
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, why don't you contact the developer? You can find his name and email address in the first bits of each file.

cereal 1,524 Nearly a Senior Poster Featured Poster

Whoops! I'm sorry, I did a mistake when I defined the default values, change lines from 11 to 19 with this:

$get_pages = isset($_GET['page']) ? $_GET['page'] : 0;

$data = array(

    'options' => array(
        'default'   => 0,
        'min_range' => 0,
        'max_range' => $pages
       )
);

And in the HTML part change this condition:

if($number <= 1)

To:

if($number <= 0)

So, when ?page= is not defined or is 0 it will return 0,3 i.e. the first three posts, page=1 will return 3,3, page=2 will return 6,3 and so on... I think it should work fine now.

Going to your questions:

What does floor do here?

$pages = floor($posts / $perpage);

Floor is a function to round fractions down, if you do 15 / 2 you get 7.5, by using floor you get 7, you can decide to round always up by using ceil() or to depend on the value with round() ( by default this function rounds down when the decimal is .4 or lower, with .5+ rounds up), for example:

$n = 15 / 2;
echo floor($n); # 7
echo ceil($n);  # 8
echo round($n); # 8

In this case, if we round up, the last page will be empty.

Docs:

What does this line say?

This line is an IF statement, defined with the ternary operator ?::

$get_page = isset($_GET['page']) ? $_GET['page'] : 0;

It is a short …

cereal 1,524 Nearly a Senior Poster Featured Poster

The trim() function is used to remove leading and trailing spaces, for example:

$a = ' 1';
var_dump($a);

Outputs: string(2) " 1", instead:

$b = trim($a);
var_dump($b);

Outputs: string(1) "1"

As you see, it removes the extra space, but it returns always a string, not an integer type, to get an integer you can do:

$c = (int)$b;
$d = intval($b);

But you still need to validate the input, so in this case you can use filter_var() where:

  1. the first argument is the string;
  2. the second argument is a constant to define the type of validation or sanitazation;
  3. the third argument in this case is an array with a default value, in case the user submits something else, like a negative number or word values, and it is useful if you want to stop at a defined value.

So:

$e = filter_var($b, FILTER_VALIDATE_INT);

In all these cases ($c, $d and $e) var_dump will return:

int(1)

Not anymore string. Some information here:

I want each page to show only 3 posts to the user, so posts 1-2-3 go into page 1, and posts 4-5-6 go into page 2, and posts 7-8-9 go into page 3.

Now, what you're searching for is pagination. In practice you have to define how many posts you want to display for each page, in your case 3, so we need to define the boundaries, …

cereal 1,524 Nearly a Senior Poster Featured Poster

My fault, sorry: you have to pass an integer to the bind method, from the form it receives a string and so the query will output badly, something like:

LIMIT "1', 3'"

I was testing from command line. Add the filter_var() and it will work properly:

$number = trim($_POST['number']);
$number = filter_var($number, FILTER_VALIDATE_INT);

$stmt = $conn->prepare("SELECT ID, Title, Author, Content FROM Posts LIMIT :limit, 3");
$stmt->bindParam(':limit', $number, PDO::PARAM_INT);

In addition, with the filter_var() function you can define a range of valid values, for example:

$data = array(
    'options' => array(
        'default'   => 1,
        'min_range' => 1,
        'max_range' => 100
       )
);

$number = filter_var($number, FILTER_VALIDATE_INT, $data);

Last, add the name attribute to your submit button, otherwise this statement if(isset($_POST['submit'])) will fail:

<input type="submit" name="submit" value="Submit">
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, it works fine for me. Can you show your current code?

cereal 1,524 Nearly a Senior Poster Featured Poster

It returns boolean (FALSE in this case) because the query will generate an error, due to a quote placed in the wrong place s.type='c)', so change this:

$sql = "SELECT s.*, u.avatar 
    FROM status AS s
    LEFT JOIN users AS u ON u.username = s.author
    WHERE (s.account_name = '$u' AND s.type='a') 
    OR (s.account_name='$u' AND s.type='c)'        -- error
    ORDER BY s.postdate DESC LIMIT 20";

To:

$sql = "SELECT s.*, u.avatar 
    FROM status AS s
    LEFT JOIN users AS u ON u.username = s.author
    WHERE (s.account_name = '$u' AND s.type='a') 
    OR (s.account_name='$u' AND s.type='c') 
    ORDER BY s.postdate DESC LIMIT 20";

Since you're using MySQLi consider to use prepared statements, for some examples check this thread:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

add a space after LIMIT, at the moment when executed it will print LIMIT20, 3 instead of LIMIT 20, 3. But validate and sanitize the number. For example:

$number = trim($_POST['number']);
$number = filter_var($number, FILTER_VALIDATE_INT, $options);

$sql = "SELECT ID, Title, Author, Content FROM Posts LIMIT $number, 3";

Otherwise use prepared statements, for example:

$stmt = $conn->prepare("SELECT ID, Title, Author, Content FROM Posts LIMIT :limit, 3");
$stmt->bindParam(':limit', trim($_POST['number']), PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();

foreach($result as $key => $row) {

Docs: http://php.net/manual/en/pdostatement.bindparam.php

cereal 1,524 Nearly a Senior Poster Featured Poster

The variable $pdo, in my example, is the object that carries the connection to the database, for example:

$pdo = new PDO("mysql:dbname=DATABASE", "USERNAME", "PASSWORD");

Documentation: http://php.net/manual/en/pdo.query.php

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, if country_id is unique then you don't need the limit statement. Use mysql_fetch_row() instead of mysql_fetch_array(), but you really should not use these function anymore, these are deprecated and will be removed. With PDO you can do:

$row = $pdo->query('SELECT name FROM countries WHERE country_id = 15', PDO::FETCH_OBJ)->fetch();

echo $row->name;
cereal 1,524 Nearly a Senior Poster Featured Poster

The function mysql_result() returns one of the rows of the result set, so if you get a total of 10 rows, you can decide to get one of those:

$query = mysql_query('SELECT * FROM tablename');
$row   = mysql_result($query, 2);

the count starts from 0.

To get a single row, instead, use the limit statement:

$query = mysql_query('SELECT * FROM tablename WHERE country_id = 15 LIMIT 1');

Docs: https://dev.mysql.com/doc/refman/5.6/en/select.html

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

the function array_diff() will return empty:

  1. if the first array is smaller then the second;
  2. and if the elements in the first array range are the same of the second.

For example:

$a = [1,2];
$b = [1,2,3];

print_r(array_diff($a, $b);

Will return empty, instead:

$a = [1,2];
$b = [1,4,3];

print_r(array_diff($a, $b);

Will return 2. This:

$a = [1,2];
$b = [1,4,3];

print_r(array_diff($b, $a);

Will return 4 and 3, because in this case the size of the first array ($b) is larger. So if you compare the sizes you can decide which submit as array1 and which as array2. Does this help?

To compare I would serialize them to get a digest, for example:

<?php

    $a = [
        0 => ['a' => '1'],
        1 => ['a' => '1', 'b' => '2'],
    ];

    $b = [
        0 => ['a' => '1'],
        1 => ['a' => '1', 'b' => '3'],
        2 => ['a' => '1', 'b' => '2', 'c' => '3'],
    ];

    function generate_digest($array)
    {
        $str = serialize($array);
        return md5($str);
    }

    function my_diff($first, $second)
    {
        $n1 = count($first);
        $n2 = count($second);

        if($n1 >= $n2)
            return array_diff($first, $second);

        return array_diff($second, $first);
    }

    $first  = array_map('generate_digest', $a);
    $second = array_map('generate_digest', $b);
    $diff   = my_diff($first, $second);

    print_r($diff);

It's not a strong solution because is case-sensitive, and a simple extra space would make a difference. Anyway the function array_diff() will return the values preserving the keys, so the next step would be to get those arrays and start the other …

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

just a note: the mcrypt_ecb() function is deprecated since PHP 5.5, it means this is going to be removed. You should use mcrypt_generic()and mdecrypt_generic() as explained in the documentation:

For some information about the encryption modes check those available:

I would use CBC rather than EBC, because with EBC is possible to find patterns and it is possible to alter the encrypted string to obtain something else. This article explains the issue very well:

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi all,

@slowlearner2010

just for the log, it seems you don't need the array_push() neither the loop, use trim() to remove extra spaces and then use implode(), then you should be done:

$a = array_map('trim', $_POST['a']);
$b = implode(',', $a);

At least, looking at your example, this seems to work fine. Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

the function null2unknown() is not a PHP function, it's a user defined function so there must be a file, included by payment_gateway.php or by a main file, which defines the above function.

The GET variables, instead are usually set by form fields:

<form method="get">
    <input type="text" name="vpc_Amount">
    ...
</form>

or simply by links:

http://site.tld/payment_gateway.php?vpc_Amount=123&...

But these could be defined also by a redirect: a script that receives the form, renames the variables and then sends everything to the payment_gateway.php script:

header("Location: /payment_gateway.php?vpc_Amount=$amount&amp;...");

Which can be internal or received by another website. A lot depends on how this code is defined. If you provide more information, maybe we can help better. For example, are you using a PHP framework? Is this gateway defined for a specific credit card operator? To be more specific: is this code sending the information to a specific link? If you decide to share the full code, then remember to remove api keys, passwords and other sensitive data.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi!

The problem is caused by the quotes, you need to escape them correctly, try:

$pm_ui = '<button id="pmBtn" onclick="postPm(\''.$u.'\',\''.$log_username.'\',\'pmsubject\',\'pmtext\')">Send</button>';

In your case you're including PHP variables and your using single quotes, so you have to escape those to create the javascript arguments, and make the variables print their values. Here are few valid possible combinations:

$z = 'red';

$a = '<b class=\''.$z.'\'>Hi</b>';
$b = '<b class="'.$z.'">Hi</b>';
$c = "<b class='$z'>Hi</b>";
$d = "<b class=\"$z\">Hi</b>";

Check the docs for more information: https://php.net/language.types.string

cereal 1,524 Nearly a Senior Poster Featured Poster

It happens because you're missing the quote for the previous values, this:

('60', 'Ng\'wagindu),

should be:

('60', 'Ng\'wagindu'),
rch1231 commented: Good Eye. Was just ablut to say the same thing. +11
cereal 1,524 Nearly a Senior Poster Featured Poster

Don't rely on the value returned by the $_FILES array because is set by the client, which can be altered or simply different from what expected. For example some executives will return application/x-dosexec.

Use the finfo library:

$finfo  = new finfo(FILEINFO_MIME_TYPE);
$type   = $finfo->file($file);

if(in_array($type, array('mime', 'blacklist')))
{
    # ... deny ...
}

Docs: http://php.net/manual/en/function.finfo-file.php

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi!

Change also the value of post_max_size, this should be equal or larger than upload_max_filesize.

Docs: http://php.net/manual/en/ini.core.php#ini.post-max-size

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

the code seems fine to me. But you can try this function which extends a bit the check:

function get_ip_address()
{
    $array = array(
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
        );

    foreach($array as $key)
        if(array_key_exists($key, $_SERVER) === true)
            foreach(explode(',', $_SERVER[$key]) as $ip)
                if(filter_var($ip, FILTER_VALIDATE_IP) !== false)
                    return $ip;
}

Source: http://www.kavoir.com/2010/03/php-how-to-detect-get-the-real-client-ip-address-of-website-visitors.html

Besides: are you using Apache as webserver? Check the access and error logs for Apache and the error log for PHP, to verify if there's something wrong with your configuration. In particular the access log for Apache should save the IP address for each client request.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi there,

@Dave consider that points generated in March and April 2015 (in the range of 45 days if I'm not mistaken) are only estimated points and need to be reviewed by the team, those months are marked by an asterisk. I think there is a thread in which Dani explains how this works. Anyway I don't see the cash button just like you, but I cashed out once in June 2014, since then I accumulated ~2.4k points, not much considering your activity in just two months... :D

@ddanbe

The only thing I noticed is that they seem to slowly "evaporate" over time. :)

I saw that too, I think it's because of the considered range which is 12 months.

Bye! :)

cereal 1,524 Nearly a Senior Poster Featured Poster

@phoenix

There are some errors here:

echo work
        $sql ="UPDATE tea SET name = ' 8req'  WHERE id = '3 ' "or die ("cant update" . mysql_error());

The echo statement needs quotes if you're trying to return a string, if that is a constant it's ok, but you have to close the command with a semicolon, for example:

echo "work";

# or, for constants
echo work;

Then you've defined a query and right after or die() but:

  1. you are not running the query
  2. you are mixing in the wrong way the quotes after the query
  3. you are using MySQLi to start the connection to the database and switching to the MySQL API to return the error

So the above should look like:

mysqli_query($con, "UPDATE tea SET name = '8req' WHERE id = '3'");

if(mysqli_errno($con))
{
    echo mysqli_errno($con) . ' ['. mysqli_sqlstate($con) .']' . ': ' . mysqli_error($con);
}

To execute a query with external arguments you should use prepared statements, for some examples check this:

For the log, if using the MySQL API, then the above would look like this:

$sql = mysql_query("UPDATE tea SET name = '8req' WHERE id = '3'") or die("cant update" . mysql_error());

But is deprecated, and will be removed so, if possible, don't use it.

Last note: please next time, provide the error information here in the forum, not through a video. Bye! :)

cereal 1,524 Nearly a Senior Poster Featured Poster

The script is fine enough, I would not use the original name to save the file, because this can overwrite existing images, I would assign to each image an UUID.

But there are other steps to execute or to consider with attention:

  1. save the image into a directory in which PHP cannot be executed
  2. and process the image to remove the metadata (comment blocks, EXIF and IPTC data)

Point 1 is easy to fix, just include an .htaccess file in your images directory with the following:

SetHandler default-handler
php_flag engine off

Point 2 is not always considered, but PHP or even Javascript can be included in a perfect working image, and be executed when requested by the client, opening the website to backdoors. Disabling the PHP engine will not block the execution of Javascript: the only solution is to remove the metadata blocks from the images.

If you are not going to resize the images you can use ImageMagick to strip the metadata off, for example:

<?php

    $im = new Imagick();
    $im->readImage($image);
    $im->stripImage();
    $im->writeImage($image);
    $im->clear();
    $im->destroy();

From command line:

<?php

    $cmd = sprintf("convert --strip %s %s", $image, $image);
    system($cmd);

Some extra tools about image optimization (which can also remove metadata) can be found here:

Last note: are you using the user's email address to define the path in which you will save the images? What happens if they can change the address, the path will be renamed or you will go to …

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, getimagesize() is a function to evaluate the pixels of an image, the type and the attibutes (a stringed version of height and width), it returns an array. For example:

Array
(
    [0] => 20
    [1] => 10
    [2] => 2
    [3] => width="20" height="10"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg
)

So it is not directly used to upload an image, it is used to define the image type, and usually is used in the validation step, after the upload.

The file_get_contents() function is used to get the content from a file which can be locale or remote. The cURL library is used to perform requests to remote servers, which means it can be an upload to another server or a GET request to download an image from a remote resource (ftp, web server, API).

So the question is: are you trying to get the image from another server?

To upload an image from a client computer, instead, you need a form, basically:

<form method="post" action="upload.php" enctype="multipart/form-data"
    <label for="image">Upload an image</label>
    <input type="file" name="image" id="image" />
    <input type="submit" name="submit" />
</form>

And then, in the upload.php script, you have to check the contents of the $_FILES array:

print_r($_FILES['image']);

For more information check these docs:

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, if you're using a prepared statement to insert the data, then submit the zipcode as a string, not as integer, this should solve the issue for you. The table column must be char or varchar, as you're already doing.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi! In addition to Dave's suggestion, having a div between rows is not really correct:

<table>
    <tr>
        <td>

    <div class="img">
        <tr>
            <td><img src="..." />
    </div>

    <tr>
        <td>
</table>

Do:

<table>
    <tr>
        <td>

    <tr>
        <td><div class="img"><img src="..." /></div>

    <tr>
        <td>
</table>

Or simply:

<table>
    <tr>
        <td>

    <tr>
        <td><img class="img" src="..." />

    <tr>
        <td>
</table>

If necessary. Otherwise you can append the class to the td tag.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, it seems fine to me, but you can use directly the object created by the diff() method, without formatting the output, as in my previous example:

$minutes  = 0;
$minutes += $diff->h * 60;
$minutes += $diff->i;

echo round($minutes / 4);

Which outputs 23, with floor 22. If you do print_r($diff) you will see:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 1
    [i] => 30
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 0
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

use the DateTime library, in particular look at the diff() method. For example:

<?php

    $one = '09:30AM';
    $two = '06:30PM';

    $dtime_1 = new Datetime($one);
    $dtime_2 = new Datetime($two);

    $diff = $dtime_1->diff($dtime_2);
    echo $diff->format('%H:%I');

Will print 09:00. More info here:

cereal 1,524 Nearly a Senior Poster Featured Poster

@Wojciech_1 with here I mean here in Daniweb ;D

cereal 1,524 Nearly a Senior Poster Featured Poster

Maybe Shift Tab? It seems free, at least in Ubuntu.

Well, I didn't thought it was already in use here, to move the code blocks: TAB forward, Shift TAB backward. It's time for a vacation...