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) {
    // Check if the input is a valid number
    if (typeof number !== 'number' || isNaN(number)) {
        console.log("Invalid input: Please enter a valid number.");
        return;
    }

    // Check if the number is even or odd
    if (number % 2 === 0) {
        console.log(`${number} is an even number.`);
    } else {
        console.log(`${number} is an odd number.`);
    }
}

// Example usage:
checkEvenOdd(10);  // Output: 10 is an even number.
checkEvenOdd(7);   // Output: 7 is an odd number.
checkEvenOdd("abc"); // Output: Invalid input: Please enter a valid number.

How it works:

  1. The function checkEvenOdd takes a parameter number.
  2. It first checks if the input is a valid number using typeof and isNaN().
  3. If valid, it checks whether the number is even or odd using the modulus operator %.
  4. If number % 2 === 0, the number is even; otherwise, it is odd.
  5. The result is printed using console.log().

Purpose 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 creating a connection before executing queries.

Syntax

mysqli_connect(host, username, password, database_name, port, socket);

Parameters

Parameter Description
host The hostname or IP address of the MySQL server (default: "localhost").
username The username for authentication.
password The password for authentication.
database (Optional) The name of the database to connect to.
port (Optional) The port number (default: 3306).
socket (Optional) The Unix socket file path (Linux/Unix systems).

Usage Example

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

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

Key Points

  • 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.
  • The mysqli extension is preferred over the older mysql_* functions, which are deprecated.

Discussion

Loading…

More Computer Science questions

All Computer Science old questions