0

I am not sure where to enter the additional php you provided.

Do not consider it anymore, I thought the request and response was between PHP pages and I was suggesting you to move the client to a landing page. In this case you probably need more an header with a status code.

A question: are you sure you are sending a POST request to the script? This error:

"Warning: mysqli_close() expects parameter 1 to be mysqli, null given in"

with the code of your first post, can raise only if the request method is not POST.

Do this test: at the end of the POST statement print the request method:

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
    # your code here
}

echo 'Current request method: ' . $_SERVER['REQUEST_METHOD'];

And see what you get.

0

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 ...

0

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.

2

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?

0

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.

0

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.

2

@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.

2

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.

Votes + Comments
Good shout about multiple tabs +1 - a common gotcha!
2

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!

Votes + Comments
Excellent, as usual.
1

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.

1

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;
0

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... ^_^