Computer ScienceNEB 2081

Write a JavaScript function that checks if a number is even or odd and print the result. [1+4] OR What is purpose of the mysqli connect ( ) function in PHP ? Describe its usage and parameters. [2+3]

5

Answer

JavaScript Function to Check Even or Odd

function checkEvenOdd(number) {
    if (number % 2 === 0) {
        console.log(`${number} is an even number.`);
    } else {
        console.log(`${number} is an odd number.`);
    }
}

// Example usage:
checkEvenOdd(4);  // Output: 4 is an even number.
checkEvenOdd(7);  // Output: 7 is an odd number.

Explanation:

  1. The function checkEvenOdd takes a single parameter number.
  2. It checks if the number is divisible by 2 using the modulus operator (%).
    • If number % 2 === 0, the number is even.
    • Otherwise, it is odd.
  3. The result is printed using console.log() with a formatted string.

Purpose and Usage of mysqli_connect() in PHP

Purpose:

The mysqli_connect() function in PHP is used to establish a connection to a MySQL database using the MySQL Improved (mysqli) extension. It allows PHP scripts to interact with MySQL databases by sending queries and retrieving results.

Syntax:

mysqli_connect([string $host = "localhost"], [string $username = ""], [string $password = ""], [string $database = ""] [, int $port = 3306] [, string $socket = ""])

Parameters:

Parameter Description Default Value
$host Database server hostname (e.g., "localhost" or "127.0.0.1"). "localhost"
$username Database username. "" (empty)
$password Database password. "" (empty)
$database Database name (optional). "" (empty)
$port Database port number (default: 3306). 3306
$socket Unix socket path (Linux/Unix systems). "" (empty)

Example Usage:

<?php
$conn = mysqli_connect("localhost", "root", "password", "test_db");

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} else {
    echo "Connected successfully!";
    mysqli_close($conn); // Close connection when done
}
?>

Key Notes:

  • Always check if the connection is successful using mysqli_connect_error().
  • Use mysqli_close() to free up resources after database operations.
  • For security, avoid hardcoding credentials; use environment variables or configuration files.

Discussion

Loading…

More Computer Science questions

All Computer Science old questions