Category: PHP

  • Connecting PHP with MySQL

    <?php
    $conn = new mysqli("localhost", "root", "", "testdb");
    
    if ($conn->connect_error) {
    
    die("Connection failed: " . $conn-&gt;connect_error);
    } echo "Connected successfully!"; ?>

    Explanation:

    • mysqli is used to connect PHP with MySQL database.
    • Replace "localhost", "root", "", "testdb" with your DB credentials.
  • Form Handling

    Create a file form.html:

    <form method="GET" action="welcome.php">
      Name: <input type="text" name="username">
      <input type="submit">
    </form>
    

    In welcome.php:

    <?php
    echo "Welcome " . $_GET["username"];
    ?>
    

    Explanation:

    • When you submit the form, username value is sent to welcome.php.
    • Example: If you type Saim, it shows Welcome Saim.
  • Associative Arrays

    <?php
    $person = [
    
    "name" =&gt; "Ali",
    "age" =&gt; 30,
    "city" =&gt; "Karachi"
    ]; echo $person["name"]; // Ali ?>

    Explanation:

    • Associative arrays use key-value pairs.
    • You can access values using their keys.
  • Functions Example

    <?php
    function greet($name) {
    
    return "Hello, $name!";
    } echo greet("Saim"); ?>

    Explanation:

    • Functions are created with function.
    • You can pass parameters ($name).
    • Output: Hello, Saim!
  • Arrays Example

    <?php
    $fruits = ["Apple", "Banana", "Orange"];
    
    foreach ($fruits as $fruit) {
    
    echo $fruit . "&lt;br&gt;";
    } ?>

    Output:

    Apple  
    Banana  
    Orange
  • While Loop

    <?php
    $i = 1;
    while ($i <= 3) {
    
    echo "Count: $i &lt;br&gt;";
    $i++;
    } ?>
  • Loops Example

    (a) For Loop

    <?php
    for ($i = 1; $i <= 5; $i++) {
    
    echo "Number: $i &lt;br&gt;";
    } ?>

    Output:

    Number: 1  
    Number: 2  
    Number: 3  
    Number: 4  
    Number: 5
  • If-Else Example

    <?php
    $marks = 75;
    
    if ($marks >= 50) {
    
    echo "You passed!";
    } else {
    echo "You failed!";
    } ?>

    Explanation:

    • If condition is true, “You passed!” will be printed.
    • Otherwise, “You failed!” is shown.
  • Data Types

    <?php
    $number = 100;        // Integer
    $price = 99.99;       // Float
    $name = "PHP";        // String
    $is_active = true;    // Boolean
    ?>
    

    Explanation:
    PHP supports int, float, string, boolean, array, object, null types.

  • Variables in PHP

    <?php
    $name = "Saim";
    $age = 25;
    
    echo "My name is $name and I am $age years old.";
    ?>
    

    Explanation:

    • Variables in PHP start with $.
    • Strings inside double quotes can include variables.
    • Output: My name is Saim and I am 25 years old.