Thursday 19 January 2017

PHP & SQL - Basic sending of info to database

In order to become familiar with PHP's syntax and sending data to the SQL database I created a simple test that allows the user to input their first and last name. Once submitted it sends that information to the database, creating a new place for them in the database array.

Here is the test on my website:
http://clymsmith.co.uk/Clym_Test/

This is comprised of two pages;
index.php
welcome.php


Inside the HTML of index.php, I just use a basic form, which once submitted takes the user to another page that lists all the current users. I also use some of the PHP code from the next page, to print to the HTML page all the current names in the database - just as an extra personal feature.

<form action="welcome.php" method="post">
First Name: <input type="text" name="f_name"><br>
Second Name: <input type="text" name="s_name"><br>
<input type="submit">


The code for welcome.php:

First of all inside the php tag, I set the variables up for; server, username, pass and database name. Because the PHP file will be executed on the host server, I use 'localhost'. I use the f_name and s_name from the form on the previous page, saving it to variables that are used later to send to the database.

<?php
$servername = "localhost";
$username = "*******";
$password = "*******";
$dbname = "*******";
$F_name = $_POST['f_name']; 

$S_name = $_POST['s_name'];

Next up, I create a new variable called $conn which creates a new mysqli connection, and it passses through the servername, user, pass and dbname variables. Following that I used a if statement to check if there is a connect error, and if so to kill the connection script. For this I use the object-oriented way ($conn->connect_error) vs procedural (conn_connect_error (void)).

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);



Next, it takes the info stored in the $F_name and $S_name variable, and stores it in the $sql variable.

$sql = "INSERT INTO  (*dbname*) (f_name, s_name)

VALUES ('$F_name', '$S_name')";

Next up is the $sql2 variable, in this I use the SELECT statement to grab the id, f_name, s_name from the database (I replaced the actual database name with '(*dbname*)' instead for privacy - just so you get an idea). I also create a $result variable which stores the connection result and uses the $sql data.

$sql2 = "SELECT id, f_name, s_name FROM (*dbname*)";
$result = $conn->query($sql);

Next I use a if statement to check if the resulting number of rows is greater than 0. If it is, then I use a while loop, to create the HTML that will display the new content (using first name and second name). To finish it off I close the connection.

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<br>First Name: ". $row["f_name"]. "<br> "."Second Name: " . $row["s_name"] . "<br>";
     }
} else {
     echo "0 results";
}

$conn->close();

?>  



Wednesday 18 January 2017

CSS3 & HTML - creating webpages that change for mobile

Making sure that a webpage is mobile friendly can be a challenge for sure. However with the @media query in CSS it can be made a bit easier.

Here is an example that means that IF the width of the screen is greater than 480, then the following rules apply - background-color: lightgreen;

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    
}
}


With that in mind, you can then go ahead and make things position better, because inside of that @media screen query you can go ahead and change the size of text, move things around, cancel out objects etc. It's really a very useful feature to utilize if you're building up a webpage from scratch, or even making a page mobile friendly.

Tuesday 17 January 2017

Javascript & HTML canvas - randomly generated grey scale value

Link to finished example:
http://www.w3schools.com/code/tryit.asp?filename=FBSXKSA3CNK6

I have been playing with and learning more about Javascript and the <canvas> feature for a bit and to be honest there have been some bits that are confusing. But I have finally managed to create a randomly generated 2d cube-map (I also added in a update function which makes it recreate the random map every 200 milliseconds).



Set up the <canvas>

Firstly I created the HTML canvas, which is 500 x 500px, has an ID of 'myCanvas' and set the border to red in the styling:

<canvas id="myCanvas" width="500" height="500" style="border:4px solid red;">


Javascript creating the canvas

Next it's jumping into Javascript and I grab the canvas element from the HTML, and set it's type to 2D storing them in the canvas and context variable.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');


More variables..

Also in the initial stages I've set up variables to create how many squares wide and high, and created an empty array that will store the colours later.

 var cols = 17;
 var rows = 17;
 var colors = [];

Next , I set up the function which executes 'functionGo' every 200 milliseconds using the Javascript window.setInterval to do so.

window.setInterval(functionGo, 200);

Next up, I create a function which is used later to create a random number between min and max value. 

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


Finally I will create the function functionGo that creates the cubes. So to break it down:

- First for loops, which cycles through the array (colors), and creates a new array per spot - the length of that loop is determined by the cols variable which currently is 17. So it creates 17 new array's. (basic multi-dimensional array).
- Second for loop, which cycles through each new array created and sets variable x and y, to the current position * 30 (each square is 30x30). Then for each spot, a square is created with the beginPath() function, rect() function, fillStyle() function (the colour is generated using the random number generator we created earlier. Between the values 20-100.), and finally the fill() function.

function functionGo() {
for(var i=0; i<cols; i++) {
           colors[i] = [];
     for(var j=0; j<=rows; j++) {
             var x = i * 30;
             var y = j * 30;
                            
        context.beginPath();
context.rect(x, y, 30, 30);
context.fillStyle = ('hsl(0,0%,' + getRandomInt(20,100) + '%)' );
context.fill();
     
         }
     }
}

And that concludes this little script that randomly generates a 17 x 17 square map in the canvas HTML element.

Monday 16 January 2017

Basic jQuery + HTML - image zoomed in on hover

For quite a while, I have been wanting to delve deeper into Javascript. On top of that there were all these other - what I thought at the time - programming names floating around that seemed super complicated and a whole confusing thing in themselves. One of these was jQuery.

However, it turns out that jQuery is just a library that uses the Javascript syntax and saves a whole bunch of time with lots of pre-build functions set in. So with that I thought I would create a really basic test using jQuery.


The idea? To zoom in on an image, once you hover over. Inspired by many different themes that are out there.


Link to example to see the result in action: http://www.w3schools.com/code/tryit.asp?filename=FBSW64JYFOVV

How it works?


Firstly for the button: 

First of all I linked to the online library of jQuery in a separate <script> tag with the following code:

src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"

then In a separate <script> tag I'll create the main function using the basic jQuery syntax: $(selector).action():

$(document).ready(function(){

}

Setting up the function 

So with that, inside of the main 'document' function I use $ then reference to the id "button" that is in my HTML code using the .click action set by the jQuery library. Finally, with that set I can then get a reference to the <div> element in the HTML document. I have 2 different <div> each either own ID ('#div1' and '#div2'). Once referenced I can assign the jQuery action which in this case is a basic fadeIn set to 'slow' for the first, and '3000' milliseconds for the second one.

 $("button").click(function(){
        $("#div1").fadeIn("slow");
        $("#div2").fadeIn(3000);
 });

Mouse over/out <div>

With that set I can then go ahead and write the code for when the mouse hovers over the element. For this, I used the .animate action, setting the width and height to 500% and after some playing around I came to the following values for marginLeft and marginTop.

$("#div2").mouseover(function(){    
    $("#img2").animate({
            width: '500%',
            height: '500%',
            marginLeft: '-=200px',
            marginTop: '-=80px',
         });
});

Then when the user takes their mouse away, I would reset the values to these:

 $("#div2").mouseout(function(){    
    $("#img2").animate({
            width: '300%',
            height: '300%',
            marginLeft: '-180px',
            marginTop: '-20px',
        });
});


Finished code

Once the first <div> was set up, I copied the function and tweaked the values slightly. In hindsight It would have been beneficial to create one function that handled the whole mouse over/out and then call that function with the new values. 
Here is the final code:

$(document).ready(function(){
    $("button").click(function(){
        $("#div1").fadeIn("slow");
        $("#div2").fadeIn(3000);
    });
$("#div2").mouseover(function(){    
    $("#img2").animate({
        width: '500%',
            height: '500%',
            marginLeft: '-=200px',
            marginTop: '-=80px',
            
        });
        });
     $("#div2").mouseout(function(){    
    $("#img2").animate({
        width: '300%',
            height: '300%',
            marginLeft: '-180px',
            marginTop: '-20px',
        });
        });
        
    $("#div1").mouseover(function(){    
    $("#img1").animate({
        width: '100%',
            height: '100%',
            marginLeft: '0px',
            marginTop: '0px',
            
        });
        });
     $("#div1").mouseout(function(){    
    $("#img1").animate({
        width: '300%',
            height: '300%',
            marginLeft: '-180px',
            marginTop: '-20px',
        });
        });
        

});