cereal 1,524 Nearly a Senior Poster Featured Poster

Okay,

if the register request is sent to another script you have to redirect the client back to a page that can accept GET requests. Which can be the sign in page or the sign up in case the registration failed. So at the end of the script, right after mysqli_close() you would write:

header('Location: http://site/login');
exit;

You could work on the statements to define the header location string and redirect the user to the appropriated page, depending on the results, for example:

<?php

# use session to save the error message
session_start();

if($_SERVER['REQUEST_METHOD']=='POST')
{
    include 'DatabaseConfig.php';

    # default location
    $location = 'Location: http://site/sign_in';

    # default message
    $_SESSION['msg'] = 'Registration Successfully.';

    $con = mysqli_connect($localhost,$username,$password,$database);
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $CheckSQL = "SELECT * FROM users WHERE email='$email'";
    $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));

    if(isset($check))
    {
        $_SESSION['msg'] = 'Email Already Exist.';
        $location = 'Location: http://site/sign_up';
    }

    else
    { 
        $Sql_Query = "INSERT INTO users (username,password,email) values ('$username','$password','$email')";

        if( ! mysqli_query($con,$Sql_Query))
        {
            $_SESSION['msg'] = 'Something went wrong.';
            $location = 'Location: http://site/sign_up';
        }
    }

    mysqli_close($con);
    header($location);

    # exit to force the redirect
    exit;
}

Then on the landing pages you start the session again, get the message if it exists and unset, so that next request does not carry the old message:

<?php

# initialize the session
session_start();

# initialize the variable
$msg = '';

if(TRUE === array_key_exists('msg', $_SESSION))
{
    $msg = $_SESSION['msg'];
    unset($_SESSION['msg']);
}

# print the message where needed...

What you still need to do, as suggested by Diafol, is to …

cereal 1,524 Nearly a Senior Poster Featured Poster

When I remove the extra bracket, I get this "Parse error: syntax error, unexpected end of file".

I suggested you to move mysqli_close() inside the statement, not to remove the extra bracket. Otherwise you get the syntax error.

cereal 1,524 Nearly a Senior Poster Featured Poster

At line 26 there is an extra }, but it does not raise a syntax error, so if on top you have a condition like:

if($_POST)
{
    # open connection here
    # other code ...
} # <-- line 26 in your code
# close connection here

then, when you open the page with a GET request, you get the error because the connection object does not exists. If this is the case, move close() into the statement and it should work.

cereal 1,524 Nearly a Senior Poster Featured Poster

From the documentation:

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

It is like doing:

echo 'hello';
exit;
echo 'world';

so in your function you can store the value that you want to return into a variable, you can use the assignment operator .= and then return the variable at the end of the function execution:

function generate_list($rows)
{
    # initialize the $str variable
     $str = "
     <table>
     <tr>
         <th>Firstname</th>
        <th>Sirname</th>
        <th>Email</th>
        <th>Phonenumber</th>
        <th>Information</th>
     </tr>";

     while($row = $rows->fetch_assoc())
     {
         # append values to the $str variable
         $str .= "
         <tr>
            <td>{$row['Firstname']}</td>
            <td>{$row['Sirname']}</td>
            <td>{$row['Email']}</td>
            <td>{$row['Phonenumber']}</td>
            <td>{$row['Information']}</td>
        </tr>";
     }

     # append values to the $str variable
     $str .= "</table>";

     # finally return the contents of $str
     return $str;
}

$results = $con->query("SELECT * FROM listing");

# store the results of the function into $list
$list = generate_list($results);

# print the contents of $list when needed
echo $list;

$results->free();
$con->close();

About the connection to the database, you could set that outside of the function scope, what happens if you have 30 functions pulling results from the database and you have to change the credentials?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi Julie,

if the OS set the azerty layout try to press shift and comma to get the question mark. Anyway you should set the keyboard layout to match the keyboard not the language of the OS, see if this helps:

Also from the Lenovo documentation for your laptop, you can get the original layout name, set that and it should work fine again.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, which version of curl are you using? I don't have the -W option and I don't find it in the documentation.

Have you tried the PHP curl library? http://php.net/manual/en/book.curl.php
Also you could use Guzzle: http://docs.guzzlephp.org/en/latest/

An example with Guzzle:

<?php

require_once dirname(__DIR__) . '/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$config = ['connect_timeout' => 30
         , 'timeout' => 30
         , 'debug'   => TRUE
         , 'headers' => ['Authorization' => 'Token r4r4xxxxx']];

$client   = new Client();
$resource = fopen(tempnam('/tmp/', 'image_'), 'w');
$request  = new Request('GET', 'https://link/to/api/');

$client->send($request, array_merge($config, ['sink' => $resource]));

If you run this into a terminal you can see a verbose log of request and response, to disable just set debug to false or simply remove it from the config array.

cereal 1,524 Nearly a Senior Poster Featured Poster

@UI

Hi!

in addition to previous comments, if you are learning PHP for work, sooner or later you will handle legacy code, you will be asked to add functionalities, not always to port it. You cannot always choose the version to work with. For example, something simple like:

$i = 1024**2*10;

returns a syntax error if you use PHP <= 5.5 and works fine when using the latest versions. To avoid issues in such case, you would write:

$i = 1024*1024*10;

Or see how list() changed the behaviour between PHP 5 and 7 when using array indices, that's just insane (it was from the beginning). IMHO, you need to know these things too, to become more efficient.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

what have you done so far?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hmm, the session in this case it is not, probably, the best approach: what happens if, in the current session, you open multiple tabs of A.php with different IDs?

A.php?id=123
A.php?id=124
A.php?id=125
...

It would screw up, because the session value would be rewritten by the latest loaded tab. Append the query string to B.php, so if you are using a form you can do:

<form method="get" action="B.php?id=123">

Or hide it in the input fields:

<input type="hidden" name="id" value="123">

If you want more appropriated help, share an example of what you are trying to do.

diafol commented: Good shout about multiple tabs +1 - a common gotcha! +0
cereal 1,524 Nearly a Senior Poster Featured Poster

Whenever I press a button on B.php, the value ID=1 gone.

Can you clarify this? Right now it seems the issue is not related to A.php but just to what happens inside B.php.

cereal 1,524 Nearly a Senior Poster Featured Poster

Right now, change line 13 to:

if(mysqli_num_rows($query_run)>0)

There is also another error here:

$query_run = mysqli_query($query,$db);

The first argument of the function must be the link to the database, the second the query statement. So:

$query_run = mysqli_query($db, $query);

Regarding prepared statements you have to change the approach and use the MySQLi Prepared Statement class. You can find the documentation here:

So, define the query to perform:

$query = "SELECT * FROM `tbl_employee_information` WHERE `employeeno` = ? AND `name` = ?";

Instead of writing variables directly inside the query string, replace them with placeholders and bind the parameters through the bind_param() function.

MySQLi allows procedural and object oriented styles.

Procedural style:

$stmt = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($stmt, 'is', $empNo, $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);

if(0 < mysqli_stmt_num_rows($stmt))
{
    # code
}

mysqli_stmt_free_result($stmt);

The object oriented style looks like:

$stmt = $db->prepare($query);
$stmt->bind_param('is', $empNo, $name);
$stmt->execute();
$stmt->store_result();

if(0 < $stmt->num_rows)
{
    # code
}

$stmt->free_result();

The is stands for i integer, s string, for the $empNo and $name variables. You can find which types you can define, inside the bind_param() function documentation.

A word on $empNo and $name, you are currently using $_POST, use filter_input(), instead, as you can sanitize the input:

$empNo = filter_input(INPUT_POST, 'employeeno', FILTER_SANITIZE_NUMBER_INT);
$name = filter_input(INPUT_POST, 'employeeno', FILTER_SANITIZE_STRING);

The docs about the filters:

Bye!

diafol commented: Excellent, as usual. +15
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

this mysq_num_rows() does not exists, you may want to use:

http://php.net/mysqli_num_rows

A part that, don't forget to use prepared statements, otherwise sooner or later you may receive a visit from Bobby Tables.

cereal 1,524 Nearly a Senior Poster Featured Poster

You're welcome! Look at lines 179 and 187. In the first case you have to close the PHP tag ?>, in the second case you have:

//Display iFrame.?>

Here the closing tag is hidden by the comment //.

cereal 1,524 Nearly a Senior Poster Featured Poster

It's line 4:

echo '<td>'.<img  src='images/blank_big.jpg' height='150px;' width='150px;' />.'</td>';

The way you are using the concatenation operator (dot operator) is not correct, as <img ... is a string, so it must be quoted. Do:

echo "<td><img src='images/blank_big.jpg' height='150px' width='150px' /></td>";

Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

in this case the error message is very descriptive:

PHP Parse error: syntax error, unexpected '"', expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/sn/public_html/sn/home.php on line 168

It points to a specific file and line of the code. If you don't find the error in that line then search above. On line 133 of home.php there is a backtick:

exit();` // <-- remove this

If you want to learn PHP, learn to reproduce bugs: isolate the code that generates the error and try to get the same error message:

<?php

print 'hello';`
print 'world';

Generates:

PHP Parse error: syntax error, unexpected end of file, expecting '`' in /tmp/a.php on line 5

Also the backtick operator as a specific meaning in PHP as it's an alias of shell_exec(), you can run a command like this:

$arg  = array_key_exists(1, $argv) ? escapeshellarg($argv[1]) : '';
print `find . -type f -iname "$arg" 2> /dev/null`;

> php a.php *.jpg

More info: http://php.net/manual/en/language.operators.execution.php
The comment part of the manual, sometimes, is very useful.

cereal 1,524 Nearly a Senior Poster Featured Poster

Test: https://http2.akamai.com/demo

//Okay, it's not due to HTTP/2 :p

cereal 1,524 Nearly a Senior Poster Featured Poster

Hello,

please share the code otherwise we cannot help.

diafol commented: For your politeness :) +15
cereal 1,524 Nearly a Senior Poster Featured Poster

It is really sad, I have used a lot and I have been a volunteer editor for few years sometime ago. Is there anything else similar?

cereal 1,524 Nearly a Senior Poster Featured Poster

Remove or comment lines from 13 to 19, i.e. these:

$event_type = "";   
$event_date = "";   
$event_country = "";   
$event_postcode = "";   
$event_title = "";   
$event_description = "";   
$event_ltm = ""; 

Because with these you are resetting the values assigned in the previous lines (from 5 to 11) to the same variables.

cereal 1,524 Nearly a Senior Poster Featured Poster

Okay,

a part lines from 13 to 19, which are blanking the variables and I suppose it's just an error here in the paste, at line 21 (the $query) you have " or die(mysqli_error($conn)); at the end of the string, so when you run the query at line 22, it will fail, change this:

$query = "INSERT INTO meets (`event_type`,`event_date`,`event_country`,`event_postcode`,`event_title`,`event_description`,`event_ltm`) VALUES ('$event_type','$event_date','$event_country','$event_postcode','$event_title','$event_description','$event_ltm')" or die(mysqli_error($conn));

To:

$query = "INSERT INTO meets (`event_type`,`event_date`,`event_country`,`event_postcode`,`event_title`,`event_description`,`event_ltm`) VALUES ('$event_type','$event_date','$event_country','$event_postcode','$event_title','$event_description','$event_ltm')";

And try:

$result = mysqli_query($conn, $query);

if( ! $result)
    print sprintf('Error (%s) %s', mysqli_errno($conn), mysqli_error($conn));

You could also print the $query statement and try if it works fine through a MySQL client:

print $query;
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

can you show the insert query? Also if you add error checking do you get any additional information?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi Janice,

the error is given by this $_SESSION['last_id'], because is not set. Before running the query you can make sure the index is set by running:

if(TRUE === array_key_exists('last_id', $_SESSION))
{
    # execute query
}
Traevel commented: Thanks, I was a dumb +7
cereal 1,524 Nearly a Senior Poster Featured Poster

Hello, maybe you want to use something like this:

#!/usr/bin/env ruby

h = [{"gate_pass_type_id"=>2, "tag"=>0, "total"=>2000}, {"gate_pass_type_id"=>125, "tag"=>0, "total"=>300}, {"gate_pass_type_id"=>661, "tag"=>0, "total"=>750}, {"gate_pass_type_id"=>661, "tag"=>2, "total"=>100}]

n = Hash.new

h.each do |k|
    gate  = k.values[0]
    tag   = k.values[1]
    total = k.values[2]

    if(n.has_key?(gate) == true)
        n[gate] = n[gate].merge({ tag => total })
    else
        n[gate] = { tag => total }
    end
end

puts n

I also suggest for you to wait for more appropriated suggestions, as I have not used Ruby in the last decade... ^_^

cereal 1,524 Nearly a Senior Poster Featured Poster

Congrats! ^_^

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

so the validation code is not working properly.

can you give details about what does not work properly?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, do:

print_r($_GET);

inside allSearches.php and see what you get.

//Edit

Oh, wait, I'm not sure I have understood your request. You want to perform an AJAX request with the GET method?

cereal 1,524 Nearly a Senior Poster Featured Poster

Between Ask and Discussion I prefer Submit as it fits both.

Reverend Jim commented: SUBMIT. Resistance is futile ^_^ +0
cereal 1,524 Nearly a Senior Poster Featured Poster

If 2.3 in $entry['2.3'] represents the index key sent by the POST request, and so it is the name of an input field:

<input type="text" name="2.3">

then PHP will translate the dots into underscores, so you can match it by doing $_POST['2_3']. But I'm a bit lost, I am not following your issue. Maybe the AJAX does not send data? Do you see anything in the console log?

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi,

the regular expression used to validate first and last name can fail if there are special characters or a dot, like in Björk or Aldous L. Huxley, see:

So here you may want to use filter_input with FILTER_SANITIZE_STRING:

$fname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
cereal 1,524 Nearly a Senior Poster Featured Poster

Okay, maybe you want to do this inside your javascript:

var data = {'data' : JSON.stringify( _data )};
...
$.post(
      _handler,
      data
  );

Like this in the PHP side you can write:

$data = json_decode($_POST['data'], TRUE);

Sanitize and encode again and finally send the request through curl.

cereal 1,524 Nearly a Senior Poster Featured Poster

I have a form that creats a json array from user input data.
I need to send that to a php curl file so that it can be sent to an ip address.
How do I populate the curl data array from that json file?

Hello,

if remote expects json data, as it seems from the header set in the curl request, then just submit the json string as you are already doing. Use curl_error() if it seems that does not work:

You should also change this:

curl_setopt($post, CURLOPT_POST, count($data));

To:

curl_setopt($post, CURLOPT_POST, TRUE);

It should not make much difference as probably PHP will cast the integer to TRUE and curl, once CURLOPT_POSTFIELDS are set, will send a POST request anyway.

Here's an example through a test API:

<?php

$data = ['msg' => 'hello', 'token' => mt_rand(1000, 9999)];
$data_string = json_encode($data);

$post = curl_init('http://jsonplaceholder.typicode.com/posts/');

curl_setopt($post, CURLOPT_VERBOSE, TRUE);
curl_setopt($post, CURLOPT_POST, FALSE);
curl_setopt($post, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($post, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($post, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$result = curl_exec($post);

curl_close($post);

echo "RESULT:" . PHP_EOL . $result . PHP_EOL;
cereal 1,524 Nearly a Senior Poster Featured Poster

If the query does not return a result set, then the loop will not assign any value to $_SESSION and the print statement will show the previous value associated with that index: $_SESSION['status'].

I take the above for an example, but if $muser and $mypass are not set then the query will return all rows in the table.

So, if multiple rows are returned by the query, then $_SESSION will be overwritten and show the values of the last loop.

Right after session_start() add:

print print_r($_SESSION, TRUE);

This should tell you if you are carrying the value set by a previous step. Do the same after the loop. And see what you get.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hello koneill,

What happens is that even though the information page has checks that data is filled in - the checkout file if a search crawl hits the page it sends blank info to the generic e-mail box.

Is this script checking on server side too? Since you are submitting a form, you can verify if the request method is POST. That should block random crawlers, as genuine robots usually do not send POST requests.

You could also add a csrf token to the session and to the form, and verify that the request matches the one saved in the session. This should block also intentionals submissions from remote.

See:

cereal 1,524 Nearly a Senior Poster Featured Poster

@Prasanna_5

Hello, please open a new thread and search also the forum, this thread could help you:

cereal 1,524 Nearly a Senior Poster Featured Poster
cereal 1,524 Nearly a Senior Poster Featured Poster

Just tested on two others Ubuntu 16.04: 32 and 64 bit, and it works fine with the same database version. So it may be my specific box.

Thank you for support Dani and Jim!

rproffitt commented: BTW. Thanks for asking. Gave the fiddle some tries and no go there. +12
cereal 1,524 Nearly a Senior Poster Featured Poster

No, it is the latest stable version available on Ubuntu 16.04. I will try to download it from MySQL and see if it makes some difference.

cereal 1,524 Nearly a Senior Poster Featured Poster

Thank you Jim! Yes, that works fine and also counting the resulting array works fine.

The original query is not like in the above example: I was using FOUND_ROWS() in a PHP PDO class, to automatically extract the number of rows, but it was not working appropriately. So I started playing with an example table and added SQL_CALC_FOUND_ROWS too and came down with the above test.

Even by doing:

SELECT SQL_CALC_FOUND_ROWS * FROM `test` LIMIT 3;

then FOUND_ROWS() should return 5, instead it returns 1. In practice, I do not understand why it does not output the expected result.

I just did a test on MariaDB 10.0.28 and MariaDB 10.1.19 and returns 5, as expected. My current instead is 10.0.29, so it may be a bug.

//EDIT

@Dani, yes, I added SQL_CALC_FOUND_ROWS just to test the query.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hello,

so, I'm playing a bit with MariaDB 10.0.29 and I cannot understand why FOUND_ROWS() keeps returning the 1 whatever happens to the latest select query. Here's my test:

> CREATE TABLE `test` (`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, `msg` VARCHAR(100) NULL) ENGINE = InnoDB;
Query OK, 0 rows affected
Time: 0.782s

> INSERT INTO `test` (`msg`) VALUES('apples'), ('oranges'), ('strawberries'), ('cherries'), ('random');
Query OK, 5 rows affected
Time: 0.180s

> SELECT SQL_CALC_FOUND_ROWS * FROM `test`;
+------+--------------+
|   id | msg          |
|------+--------------|
|    1 | apples       |
|    2 | oranges      |
|    3 | strawberries |
|    4 | cherries     |
|    5 | random       |
+------+--------------+
5 rows in set
Time: 0.003s

> SELECT FOUND_ROWS();
+----------------+
|   FOUND_ROWS() |
|----------------|
|              1 |
+----------------+
1 row in set
Time: 0.002s

Expected result 5. The same happens with MyISAM engine.

Any clue why this happens? To avoid any possible backside issue, I have tested from a fresh connection through the command line client, but it does not seems to make difference.

The online test with MySQL 5.6, instead, returns 0, it is accessible here:

For the online test result I'm not sure it depends on SQLfiddle or it is MySQL 5.6.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, use r+ to read and write from the top or a+ in case you want to append data:

$fopen = fopen($filename, 'r+');

With the w+ flag the file is cleared:

Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

See: http://php.net/fopen

cereal 1,524 Nearly a Senior Poster Featured Poster

Indeed it was a great game! Let's see what will do Scotland now.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, codeIgniter can log errors. If enabled set it to max verbosity (through application/config/config.php) and see if it gives you some additional information.

cereal 1,524 Nearly a Senior Poster Featured Poster

That would be a big concern for sure.

cereal 1,524 Nearly a Senior Poster Featured Poster

Another random fact: sometimes in logs you see Google's bot user agent but it's just another crawler trying to avoid filters.

cereal 1,524 Nearly a Senior Poster Featured Poster

Localhost? It seems a ramsonware, a virus that encrypts data and ask money to return the files back. If you are using Windows that's probably in your system, so it should not be related to the application code. The same can happen if the folder is shared in a local network and the virus is compromising all the files it can reach.

Good luck with that.

cereal 1,524 Nearly a Senior Poster Featured Poster

Italy? :D They need to improve a lot, but here we felt the change in their approach, hope to see some great games this year!

cereal 1,524 Nearly a Senior Poster Featured Poster

Dunno, add an error check and see what you get:

if( ! $result2)
    print sprintf('Error (%s) %s', $conn->errno, $conn->error);

Note - on lines 22/23 you are accessing mysqli through procedural mode, instead of OOP, this should not make difference in the code execution, but keep it in consideration.

cereal 1,524 Nearly a Senior Poster Featured Poster

Great! I wrote the example basing on:

get_field returns false if (value == “” || value == null || value == false)

so I supposed it was returning boolean FALSE instead of mixed :)

cereal 1,524 Nearly a Senior Poster Featured Poster

This line will raise an error and kill the execution:

trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);

If you want to use it, then you have to create a condition, something like this:

if( ! $result)
    trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);

Otherwise it will run at each execution.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi! You could try with:

$url = get_field('url');

if(FALSE === $url)
{
    # code for empty value
}

else
{
    # code for assigned value
}

See: https://www.advancedcustomfields.com/resources/code-examples/#using-conditional%20statements