Php form data not submitting on mysql databse with username check - javascript

The form is loading on the registration page. But after giving any input it's not storing on MySQL database plus it also doesn't check for username availability.
Here is HTML code part:
<html>
<link type="text/css" rel="stylesheet" href="design.css">
<div class ="cus_head"> </div>
<body>
<center> <h1 style="color:#1AAB30;">Register </h1>
<form method="post" action="reg_process.php">
UserName: <input type="text" name="cus_username" >
<span class="error">* <?php echo $cus_username_err;?></span>
<span id="username_status"></span>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/users.js"></script>
<br><br>
First Name: <input type="text" name="firstname">
<span class="error">* <?php echo $firstname_err;?></span>
<br><br>
Last Name: <input type="text" name="lastname">
<span class="error">* <?php echo $lastname_err;?></span>
<br><br>
Email Id: <input type="email" name="email">
<span class="error">* <?php echo $email_err;?></span>
<br><br>
Password: <input type="password" name="password">
<span class="error">* <?php echo $password_err;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</center>
</body>
<div class ="cus_head"> </div>
Here is the Javascript file code for username availability: users.js
$('#username').keyup( function() {
var username = $(this).val();
$('#username_status').text('Searching...');
if(username !== '') {
$.post('php/username_check.php', { username: username}, function(data) {
$('#username_status').text(data);
});
}
else {
$('#username_status').text('');
}
});
Here is the PHP Part: register.php
<?php
$link = mysqli_connect("%", "****", "****", "****");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
require 'username_check.php';
// define variables and set to empty values
$cus_username = $firstname = $lastname = $email = $password = "";
// defining variable and set to empty value for error
$cus_username_err = $firstname_err = $lastname_err = $email_err = $password_err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['cus_username'])) {
$cus_username_err = "UserName is required";
} else {
$cus_username = sanitize($_POST['cus_username']);
}
if (empty($_POST['firstname'])) {
$firstname_err = "First Name is required";
} else {
$firstname = sanitize($_POST['firstname']);
}
if (empty($_POST['lastname'])) {
$lastname_err = "Last Name is required";
} else {
$lastname = sanitize($_POST['lastname']);
}
if (empty($_POST['email'])) {
$email_err = "Email is required";
} else {
$email = sanitize($_POST['email']);
}
if (empty($_POST['password'])) {
$password_err = "password is required";
} else {
$password = sanitize($_POST['password']);
}
}
// attempt insert query execution
$sql = "INSERT INTO ***** (`cus_username`, `firstname`, `lastname`, `email`, `password`) VALUES ('$cus_username', '$firstname', '$lastname','$email,'$password')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
mysqli_close($link);
?>
Here is the username_check.php
<?php
$link = mysqli_connect("%", "****", "*****", "*****");
if (isset($_POST['username']))
{
$username = sanitize($_POST['username']);
if (!empty($cus_username))
{
$sql = "SELECT *FROM ***** WHERE username = '$username'";
$count=mysqli_num_rows( $sql);
if($count==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

With reference to your username check script - as the ajax function is being triggered on keyup it is not likely that the entire field has been completed so using a like operator in the sql makes more sense.
Rather than directly embedding a variable in the sql statement it is a far better option to use prepared statements - the statement here uses a questionmark as a placeholder which is later bound to a constructed string variable containing the contents of $_POST['username'] at the time of the keyup
<?php
/*
username_check.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$rows=0;
/*
sql prepared statement using `LIKE` operator
*/
$sql='select * from `TABLE` where `username` like ?';
$stmt = $db->prepare( $sql );
if( $stmt ){
/* Bind the placeholder to an as yet undefined variable - $username */
$stmt->bind_param( 's', $username );
/* Generate the $username variable with trailing % */
$username = $_POST['username']."%";
/* Query the db */
$result = $stmt->execute();
if( $result ){
/* If the query succeeded, get the row count */
$stmt->store_result();
$rows=$stmt->num_rows;
}
/* tidy up */
$stmt->free_result();
$stmt->close();
}
$db->close();
/* Send response back to javascript callback */
exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
}
?>
For the register.php script - again using prepared statements to avoid sql injection. Neither script is tested - they are for your guidance on how you might accomplish your goals
<?php
/*
register.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql = 'insert into `TABLE` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
$stmt = $db->prepare( $sql );
if( $stmt ){
$username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
$firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
$lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
$email=!empty($_POST['email']) ? $_POST['email'] : false;
$password=!empty($_POST['password']) ? $_POST['password'] : false;
$errors=array();
if( !$username )$errors[]='Please enter a username';
if( !$password )$errors[]='Please enter your password';
if( !$email )$errors[]='Please enter your email';
if( !$firstname )$errors[]='Your firstname is required';
if( !$lastname )$errors[]='Your lastname is required';
if( empty( $errors ) ){
/* bind the variables and execute the sql statement */
$stmt->bind_param('sssss',$username,$firstname,$lastname,$email,$password);
$result = $stmt->execute();
echo $result ? 'Success' : 'Failed';
} else {
foreach( $errors as $error ){
echo $error . '<br />';
}
}
$stmt->close();
$db->close();
}
}
?>
-- Updates
The html/php page to add a new user
<?php
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Add a user</title>
<script src='//code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<style>
html, html *{font-family:calibri,verdana,arial;font-size:0.85rem;}
label{clear:both;margin:0.25rem;padding:0.25rem;display:block;width:30%;float:left;}
input[type='submit']{margin:3rem 0;background:green;color:white;clear:both;float:left;}
input[type='text'],
input[type='email'],
input[type='password']{float:right;}
#username_status{color:red;margin:0 0 0 2rem;}
</style>
</head>
<body>
<h1>Register</h1>
<form method='post' action='reg_process.php'>
<!-- the text field needs an id for the ajax function to glom onto -->
<label for='cus_username'>UserName: <input type='text' name='cus_username' id='username' /><span id='username_status'></span></label>
<label for='firstname'>First Name: <input type='text' name='firstname' /></label>
<label for='lastname'>Last Name: <input type='text' name='lastname' /></label>
<label for='email'>Email Id: <input type='email' name='email' /></label>
<label for='password'>Password: <input type='password' name='password' /></label>
<!--
various spans removed for testing
and slight rearrangement using `label`
-->
<input type='submit' />
</form>
<!--
rather than sending an ajax request with each character typed
I updated this to check for a minimal length before sending the
request and also changed the event listener to listen for blur events
so there should only be one request when the user moves to the next
field in the form
-->
<script type='text/javascript'>
$('#username').blur( function(e) {
var status=$('#username_status');
status.text( 'Searching...' );
if( $( this ).val() !== '' && $( this ).val().length > 3 ) {
$.post('php/username_check.php', { username: $(this).val() }, function(data) {
status.text( data );
});
} else {
status.text('');
}
});
</script>
</body>
</html>
<?php
/*
username_check.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$rows=0;
/*
sql prepared statement using `LIKE` operator
*/
$sql='select * from `users` where `username` like ?';
$stmt = $db->prepare( $sql );
if( $stmt ){
/* Bind the placeholder to an as yet undefined variable - $username */
$stmt->bind_param( 's', $username );
/* Generate the $username variable with trailing % */
$username = $_POST['username']."%";
/* Query the db */
$result = $stmt->execute();
if( $result ){
/* If the query succeeded, get the row count */
$stmt->store_result();
$rows=$stmt->num_rows;
}
/* tidy up */
$stmt->free_result();
$stmt->close();
}
$db->close();
/* Send response back to javascript callback */
exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
}
?>
<?php
/*
reg_process.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql = 'insert into `users` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
$stmt = $db->prepare( $sql );
if( $stmt ){
$username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
$firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
$lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
$email=!empty($_POST['email']) ? $_POST['email'] : false;
$password=!empty($_POST['password']) ? $_POST['password'] : false;
$errors=array();
if( !$username )$errors[]='Please enter a username';
if( !$password )$errors[]='Please enter your password';
if( !$email )$errors[]='Please enter your email';
if( !$firstname )$errors[]='Your firstname is required';
if( !$lastname )$errors[]='Your lastname is required';
if( empty( $errors ) ){
/* bind the variables and execute the sql statement */
$stmt->bind_param('sssss', $username, $firstname, $lastname, $email, $password );
$result = $stmt->execute();
echo $result ? 'Success' : 'Failed';
} else {
foreach( $errors as $error ){
echo $error . '<br />';
}
}
$stmt->close();
$db->close();
}
}
?>
I created these three pages following the directory structure suggested by the javascript function and form target, changed the db details to suit dev environment and assumed a table called users - ran the page and completed the form. A new user was successfully added.

Related

I want to change or remove my html element by getting URL parameters that I set after successful register

First of all I must say that I'm very new to website design and coding so please make your answer simple thanks a lot .
So I have my file register.php that contains my form .
I have my action file named register-controller.php that gets the data from user , checks it and inserts it to database .
What I need is that whenever the register is success , my form gets hidden or removed and my new div shows up that contains 'register successful' . ( On the same page "register.php" )
Can I use the variable that I passed to header "register=success" to do this action ? Should I use AJAX ? JSON ? what should I do ? Please give me the simplest answer thank you all .
MY "register.php" file contains these :
<?php
require_once "../DB/users-database.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/Header.CSS">
<link rel="stylesheet" href="/Style.CSS">
<link rel="stylesheet" href="/Footer.CSS">
<script src="https://kit.fontawesome.com/38b3678073.js" crossorigin="anonymous"></script>
<script src="../JS/main.js" async></script>
<title>ثبت نام | PCGA</title>
</head>
<body>
<?php include '../header.php' ?>
<div class="register-container">
<form action="../controllers/register-controller.php" method = "POST">
<label class = "email-label" for="email">ایمیل</label>
<input type="text" id="email" name="email" placeholder="example#example.com" value = '<?php if(isset($_REQUEST['email'])){echo $_REQUEST['email'];}else{echo '';} ?>'>
<?php
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyEmail'){
echo "<span class = 'empty-email'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidEmailFormat') {
echo "<span class = 'formaterr-email'>فرمت ایمیل نادرست است*</span>";
}
?>
<label class = "phone-label" for="phone">شماره موبایل</label>
<input type="text" id="phone" name="phone" placeholder="09xxxxxxxxx" value = '<?php if(isset($_REQUEST['phone'])){echo $_REQUEST['phone'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPhone'){
echo "<span class = 'empty-phone'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidPhoneNumber') {
echo "<span class = 'formaterr-phone'>شماره موبایل حداکثر 11 عدد است و حروف قابل قبول نیست*</span>";
}
?>
<label class = "user-label" for="username">نام کاربری</label>
<input type="text" id="username" name="username" placeholder="Username" value = '<?php if(isset($_REQUEST['username'])){echo $_REQUEST['username'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyUsername'){
echo "<span class = 'empty-user'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidUserName') {
echo "<span class = 'formaterr-user'>فرمت نام کابری نادرست است*</span>";
}
?>
<label class="pass-label" for="password">رمز عبور</label>
<input type="password" id = "password" name = "password" placeholder = "Password" >
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPass'){
echo "<span class = 'empty-pass'>فیلد نباید خالی باشد *</span>";
}
?>
<div class="checkbox-container">
<input type="checkbox" class = 'checkbox-style' name = 'rules-check'>
<label for="checkbox" class="checkbox-label">من قوانین فروشگاه را کامل مطالعه کرده ام و با آن موافق هستم</label>
<?php if (isset($_REQUEST['rules'])){
echo "<span class = 'rules-error'>قبول قوانین اجباری است و آن را حتما مطالعه کنید *</span>";
}
?>
</div>
<button type="submit" name = "submit" id="submit">ثبت نام</button>
</form>
</div>
<?php
if (isset($_REQUEST['register'])){
echo "<div class = 'register-success'>
<span class = 'register-success-span'>ثبت نام با موفقیت انجام شد</span>
</div>" ;
}
?>
<?php include '../footer.php' ?>
</body>
</html>
MY "register-controller.php" file contains these :
<?php
require "../DB/users-database.php";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit']) && $_POST['rules-check']) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
if (empty($username)){
header("Location: ../page/register.php?error=emptyUsername&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($phone)){
header("Location: ../page/register.php?error=emptyPhone&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($pass)){
header("Location: ../page/register.php?error=emptyPass&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($email)){
header("Location: ../page/register.php?error=emptyEmail&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: ../page/register.php?error=invalidEmailFormat&username=".$username."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[a-z\d_]{2,20}$/i" , $username)){
header("Location: ../page/register.php?error=invalidUserName&email=".$email."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[0-9]{11}+$/" , $phone)){
header("Location: ../page/register.php?error=invalidPhoneNumber&email=".$username."&phone=".$phone);
exit();
}
else {
$sql = "SELECT username FROM registered WHERE username = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLcheckUser");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "s" , $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rowcount = mysqli_stmt_num_rows($stmt);
if($rowcount > 0 ) {
header("Location: ../page/register.php?error=UserNameTaken");
exit();
}
else {
$sql = "INSERT INTO registered(email,phone,username,password) VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLInsert");
exit();
}
else {
$hased_pass = password_hash($pass , PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt , "ssss" , $email , $phone , $username , $hased_pass);
mysqli_stmt_execute($stmt);
header("Location: ../page/register.php?register=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
elseif (isset($_POST['submit']) && !isset($_POST['rules-check'])) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
header("Location: ../page/register.php?rules=notChecked&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
else {
header("Location: ../page/register.php?access=denied");
exit();
}
?>
You can render the part of the page you prefer depending on your URL parameters by doing
<?php
if ($_GET['success']) { ?>
<-- YOUR HTML SUCCESS CODE -->
<?php } else { ?>
<-- YOUR HTML FORM CODE -->
<?php }
?>
Ajax is the best solution for me (it can be difficult to understand but the code is clean), here an example of Ajax with your situation :
Extras is the ID of all the input in the form
Page is the PHP page to be executed (register-controller.php)
Origin is the ID where you want to put the result, Origin can be null.
(To have something in the return, you have to put an echo in the php file you specified in Page)
static Ajax(origin,Extras,page)
{
var xhr = new XMLHttpRequest();
let formData = new FormData();
for(var element in Extras)
{
if(document.getElementById(element))
{
formData.append(element,document.getElementById(element));
}
else
{
let checkbox = document.getElementsByName(element);
if(checkbox)
{
//Checkbox don't work with an ID so put instead a name
for(let i=0;i<checkbox.length;i++)
{
if(checkbox[i].checked)
{
formdata.append(element+i,"1")
}
else
{
formdata.append(element+i,"0")
}
}
}
}
}
xhr.open('POST',page);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let i= xhr.responseText;
if(origin!=null)
{
if(document.getElementById(origin) && xhr.responseText!="")
// the result document.getElementById(origin).innerHTML=xhr.responseText;
}
finish(i);
}
else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status != 200) {
// error message XHR,
let textError = "Ajax Error : " + xhr.status + ", " + xhr.statusText + ", ";
alert(textError);
}
});
// send
xhr.send(formData);
}

How to continue code to allow me to click on image and display a separate page with more info

As of right now, I am able to display my images in a single column, with an image, a title, and a small description. All of this is derived from the same database. I am not very good at coding and need some guidance, how would you add onto this existing code to 1) allow the pictures to be displayed in more than one column...and 2)allow the thumbnails to be clicked on, which will load a separate page that I can then style and list the full recipe on.
I have been messing with the code in general, and I am confused by what I created. I am not sure how to proceed.
<h2>index.php:</h2>
<section class="gallery-links">
<div class="wrapper">
<div class="gallery-container">
<?php
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM gallery ORDER BY orderGallery DESC"
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statment failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
}
?>
</div>
<?php
echo '<div class="gallery-upload">
<form action="includes/gallery-upload.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="filename" placeholder="File name...">
<input type="text" name="filetitle" placeholder="Image title...">
<input type="text" name="filedesc" placeholder="Image description...">
<input type="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>'
?>
</div>
</section>
<h2>gallery-upload.inc.php:</h2>
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
if (empty($newFileName)) {
$newFileName = "gallery";
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES["file"];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 2000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../images/gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle) || empty($imageDesc)) {
header("Location: ../index.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO gallery (titleGallery, descGallery, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../index.php?upload=success");
}
}
}
} else {
echo "File size is too big!";
exit();
}
} else {
echo "You had an error!";
exit();
}
} else {
echo "You need to upload a proper file type!";
exit();
}
<h2>dbh.inc.php:</h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gallery";
$conn = mysqli_connect($servername, $username, $password, $dbname);
Basically, you need to make a link on anchor tag which will have url of image detailed page with image id as below:
while ($row = mysqli_fetch_assoc($result)) {
// assuming that imgId is your primary key
echo '<a href="detail.php?imageId="'.$row["imgId"].' target="_blank">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
After, you need to create a new file detail.php where you can get image id by $_GET['imgId'] and then can query on that and will be able to get complete image details. You will also need to create a HTML for view and can show details.
Hope it helps you!!

How to get php echo result in javascript

I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps

Return data from database with concat

I have a textbox with the ID and NAME called "name". In my database I have firstname, preposition, lastname. In SQL I am using concat to combine these to a "name".
When I am trying to echo the result $result['name'] I get a browser error.
I guess something is wrong with the multiple variable $name = in my code. But I could not fix it.
Does someone know what is wrong with my code?
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['firstname']) ? $_POST['firstname'] : '';
$name .= isset($_POST['preposition']) ? $_POST['preposition'] : '';
$name .= isset($_POST['lastname']) ? $_POST['lastname'] : '';
$query = 'SELECT concat(firstname, ' ', preposition, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>
Edit 1:
Textbox:
<input type="text" class="form-control" id="name" name="name">
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getUser(value) { // Do an Ajax request to retrieve the product price
console.log("getUser before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/get5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getUser after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>

Autocomplete dynamic search SQL database from PHP

I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?
In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>
Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!

Categories

Resources