PHP: Passing variables from Javascript to PHP

This entry is part 54 of 54 in the series PHP Tutorial

Javascript is a client side programming language and it can’t interact with server side database such as MySQL.

If you are developing HTML 5 apps for Andoid or IOS, you will have to save some inputs into the database.  To store data, you can always pass them into php and store them using PHP.

A common technique is to use AJAX is illustrated by the example below.

ajax.html
<html>
<head>
    <script>
        function submitForm(form)
        {
            var text_input = form.inputbox.value;

            var xmlhttp=new XMLHttpRequest();

            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("text_id").innerHTML=xmlhttp.responseText;
                }
            }            
            xmlhttp.open("GET","get.php?str="+text_input,true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
<form>Enter something in the box: <br><br>
    <input type="text" name="inputbox" value=""><P>
        <input type="button" name="button" value="Click" onClick="submitForm(this.form)">
</form>
<p id="text_id">Input your name to get a response from server</p>
</body>
</html>

get.php:

<?php
$name = $_GET['str'];
echo 'Hello ' . $name . '!';
?>

Put the above 2 files, ajax.html and get.php in the same directory and run ajax.html.

You can try it here.

In the line

xmlhttp.onreadystatechange=function(){}

We put the browser in a ready state to receive a response from the server.

We then send a request to the server using:

xmlhttp.open("GET","get.php?str="+text_input,true);
xmlhttp.send();

The syntax for the method is open(method,url,async)

Method is either in post or get method, we are using get method which is faster and simpler.

async needs to be set to true to enable asynchronous rather than synchronous.

The variable will be passed into the get.php script and store as $name variable.  We can then input the $name variable into MySQL if needed.

PHP: Form with a separate php script file

This entry is part 42 of 54 in the series PHP Tutorial

As mentioned in the earliar example, we can put the php script in a separate file.

form.html
<html>
<body>

<form action="form4.php" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
</form>

</body>
</html>

Below here the separate php script file.

form4.php
<?php
$your_name = $_POST["name"];
$your_email = $_POST["email"];
echo "Welcome " . $your_name."<br>";
echo "Your Email is " . $your_email; ?>

You can try to run the page here.

The warning would not have been generated if we have 2 separate files.

Put the form.html and form4.php in the same directory, run the form.html above and it will call out the form4.php in a different file.

PHP & OOP: $this variable

This entry is part 5 of 11 in the series PHP & OOP

In this example, the $this variable is a reference to the current object, which is itself, SimpleClass.  The this reference is commonly found in other object-oriented programming languages.

<?php
class SimpleClass
{
    public $greeting = 'Hi There';
 
    public function displayGreeting() {
        echo $this->greeting;
    }
}
 
//create an instance of the class SimpleClass
$simple_object = new SimpleClass();
echo $simple_object->displayGreeting();
 
?>

The $this->greeting is to access its own variable $greeting.

If you access the $greeting variable without the $this reference, the browser will throw an undefined variable greeting error message.

You can try the below code to see the error message.

<?php
class SimpleClass
{
    public $greeting = 'Hi There';
 
    public function displayGreeting() {
        echo $greeting;
    }
}
 
//create an instance of the class SimpleClass
$simple_object = new SimpleClass();
echo $simple_object->displayGreeting();
 
?>

this_error

PHP MySQL: Outputing to table Using fetch_assoc

This entry is part 17 of 17 in the series PHP & MySQL

Continued from previous post.

In an earlier post, we have used printf to output a table records.

printf ("%d %s %s %s", $row["id"], $row["artiste"], $row["album"], $row["year"] );

If we stick to the same table format, we will have to embed the php code into the HTML table. This is what made it hard for beginners to learn PHP.

Once we have the connection to the DB set, we can use fetch_assoc to fetch the row and use echo to build up the  HTML table.

And finally we just have to use printf to output the data to the HTML table.

<table border="1">
    <tr>
        <th>ID</th>
        <th>artiste</th>
        <th>album</th>
        <th>year</th>
    </tr>
    <?php
    $mysqli = new mysqli("localhost", "root", "", "allartist");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s", mysqli_connect_error());
        exit();
    }

    $query = "select id, artiste, album, year from artist";


    if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row["id"] . "</td><td>" . $row["artiste"] . "</td><td>" . $row["album"] . "</td><td>" . $row["year"] . "</td></tr>";
            //    printf ("%d %s %s %s", $row['id'], $row["artiste"], $row["album"], $row["year"] );
        }

        /* free result set */
        $result->free();
    }

    /* close connection */
    $mysqli->close();
    ?>
</table>

If you look at the code above, and compare it with the earlier post, you could see that the main line that I have added is:

echo "<tr><td>" . $row["id"] . "</td><td>" . $row["artiste"] . "</td><td>" . $row["album"] . "</td><td>" . $row["year"] . "</td></tr>";

Running the above code will display the table below.

html_table_output

PHP MySQL: Outputing data to HTML table I

This entry is part 16 of 17 in the series PHP & MySQL

For HTML table, a basic table would look like this:

<table border="1">
    <tr>
        <th>ID</th>
        <th>artiste</th>
        <th>album</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Rod Stewart</td>
        <td>Maggie May</td>
    </tr>
</table>

We can always start from the above table and built from there.  We can for example, add one more column or one more row to the above table.

For the table that we have used, the HTML will be as below:

<table border="1">
    <tr>
        <th>ID</th>
        <th>artiste</th>
        <th>album</th>
        <th>year</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Rod Stewart</td>
        <td>Maggie May</td>
        <td>1973</td>
    </tr>
    <tr>
        <td>2</td>
        <td>New Order</td>
        <td>Substance</td>
        <td>1987</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Nirvana</td>
        <td>Smell Like Teen Spirit</td>
        <td>1992</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Rod Stewart</td>
        <td>Out Of Order</td>
        <td>1988</td>
    </tr>
</table>

The output from running the above HTML script is:

html_table