0% found this document useful (0 votes)
0 views12 pages

Scripting Language

The document provides multiple code snippets for web development tasks using PHP, HTML, and JavaScript. It includes scripts for connecting to a MySQL database, retrieving user information, form validation, displaying posts dynamically, and user registration with unique constraints. Additionally, it contains SQL queries for creating a 'users' table with specified columns.

Uploaded by

bohorajames023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views12 pages

Scripting Language

The document provides multiple code snippets for web development tasks using PHP, HTML, and JavaScript. It includes scripts for connecting to a MySQL database, retrieving user information, form validation, displaying posts dynamically, and user registration with unique constraints. Additionally, it contains SQL queries for creating a 'users' table with specified columns.

Uploaded by

bohorajames023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Write a PHP script that connects to a MySQL database and retrieves the names and email
addresses of users from a table named 'users'. Display this information in an HTML table
format.

• Source code: PHP

<?php

$servername = "localhost";

$username = "admin";

$password = "admin007";

$database = "consumers";

$conn = new mysqli($localhost, $admin, $admin007, $consumers);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT name, email FROM users";

$result = $conn->query($sql);

?>

Source code: HTML

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Information</title>
<style>

table {

border-collapse: collapse;

width: 100%;

th, td {

border: 1px solid #ddd;

padding: 8px;

text-align: left;

th {

background-color: #f2f2f2;

</style>

</head>

<body>

<h2>User Information</h2>

<table>

<tr>

<th>Name</th>

<th>Email</th>

</tr>

<?php

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

echo "<tr>";

echo "<td>" . $row["name"] . "</td>";


echo "<td>" . $row["email"] . "</td>";

echo "</tr>";

} else {

echo "<tr><td colspan='2'>No users found</td></tr>";

?>

</table>

<?php

$conn->close();

?>

</body>

</html>

2. Develop a web page with a form that includes fields for username, email, and password. Write
JavaScript code to validate the form inputs on submission, ensuring that the username is at
least 3 characters long, the email follows a valid format, and the password is at least 8
characters long. Display appropriate error messages if any input fails validation.

• Source Code: HTML

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Form Validation</title>

<style>

.error {

color: red;

</style>

</head>

<body>

<h2>Registration Form</h2>

<form id="registrationForm" onsubmit="return validateForm()">

<label for="username">Username:</label><br>

<input type="text" id="username" name="username"><br>

<span id="usernameError" class="error"></span><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email"><br>

<span id="emailError" class="error"></span><br>

<label for="password">Password:</label><br>

<input type="password" id="password" name="password"><br>

<span id="passwordError" class="error"></span><br>

<input type="submit" value="Submit">

</form>
<script>

function validateForm() {

var username = document.getElementById("username").value;

var email = document.getElementById("email").value;

var password = document.getElementById("password").value;

var usernameError = document.getElementById("usernameError");

var emailError = document.getElementById("emailError");

var passwordError = document.getElementById("passwordError");

usernameError.innerHTML = "";

emailError.innerHTML = "";

passwordError.innerHTML = "";

var isValid = true;

if (username.length < 3) {

usernameError.innerHTML = "Username must be at least 3 characters long";

isValid = false;

var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailRegex.test(email)) {

emailError.innerHTML = "Invalid email format";

isValid = false;

if (password.length < 8) {

passwordError.innerHTML = "Password must be at least 8 characters long";

isValid = false;

}
return isValid;

</script>

</body>

</html>

3. Create a PHP script that retrieves the latest 5 posts from a MySQL table named 'posts' and
formats them as JSON. Write JavaScript code to fetch this JSON data asynchronously and
display the posts dynamically on a web page. Each post should include the title, author, and
content.
• Source Code: PHP

<?php

$servername = "localhost";

$username = "admin";

$password = "admin007";

$database = "jason3";

$conn = new mysqli($localhost, $admin, $admin007, $jason3);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT title, author, content FROM posts ORDER BY created_at DESC LIMIT 5";

$result = $conn->query($sql);

$posts = [];
if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {

$posts[] = $row;

$conn->close();

header('Content-Type: application/json');

echo json_encode($posts);

?>

Source Code: HTML

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Latest Posts</title>

</head>

<body>

<h2>Latest Posts</h2>

<div id="postsContainer"></div>

<script>

fetch('latest_posts.php')

.then(response => response.json())

.then(posts => {
const postsContainer = document.getElementById('postsContainer');

posts.forEach(post => {

const postElement = document.createElement('div');

postElement.innerHTML = `

<h3>${post.title}</h3>

<p><strong>Author:</strong> ${post.author}</p>

<p>${post.content}</p>

<hr>

`;

postsContainer.appendChild(postElement);

});

})

.catch(error => console.error('Error fetching posts:', error));

</script>

</body>

</html>

4. Implement a PHP script that allows users to register by providing a username, email, and
password. Ensure that the username and email are unique and not already registered in the
database. Store the user information securely in a MySQL database table named 'users'.

• Source Code: PHP

<?php

/$servername = "localhost";

$username = "admin";

$password = "admin007";
$database = "4users";

$conn = new mysqli($localhost, $admin, $admin007, $4users);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

function sanitizeInput($input) {

return htmlspecialchars(strip_tags(trim($input)));

function hashPassword($password) {

return password_hash($password, PASSWORD_DEFAULT);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = sanitizeInput($_POST["username"]);

$email = sanitizeInput($_POST["email"]);

$password = sanitizeInput($_POST["password"]);

$sql = "SELECT * FROM users WHERE username = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("s", $username);

$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows > 0) {

echo "Username already exists. Please choose a different username.";

exit();

}
$sql = "SELECT * FROM users WHERE email = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("s", $email);

$stmt->execute();

$result = $stmt->get_result();

if ($result->num_rows > 0) {

echo "Email already exists. Please use a different email.";

exit();

$hashedPassword = hashPassword($password);

$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);

$stmt->bind_param("sss", $username, $email, $hashedPassword);

if ($stmt->execute()) {

echo "Registration successful.";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

$stmt->close();

$conn->close();

?>

Source Code: HTML

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Registration</title>

</head>

<body>

<h2>User Registration</h2>

<form action="4user.php" method="post">

<label for="username">Username:</label><br>

<input type="text" id="username" name="username" required><br>

<label for="email">Email:</label><br>

<input type="email" id="email" name="email" required><br>

<label for="password">Password:</label><br>

<input type="password" id="password" name="password" required><br>

<input type="submit" value="Register">

</form>

</body>

</html>

5. Write SQL queries to create the 'users' table with appropriate columns for username, email,
and password storage.
• Ans :

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL,

email VARCHAR(100) NOT NULL,

password VARCHAR(255) NOT NULL

);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy