PHP + MySQL - Autocomplete from database not getting data from table - php

I'm having a small college project about discussion room service. Right now I'm being tasked to implement autocomplete feature of name that orders it. I already google some tutorials. I'm not sure what went wrong, when i try to type a name, there's no data being typed ahead.
Here's my form code:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//Periksa apakah koneksi berhasil
if(mysqli_connect_errno()){
echo "Error: ";
echo mysqli_connect_error();
echo "<br /> Error Code: ";
echo mysqli_connect_errno();
die();
}
$sql = "SELECT * FROM ruangan
WHERE id = $_GET[id]";
$hasil = mysqli_query($koneksi,$sql);
$row = mysqli_fetch_assoc($hasil);
$sql2 = "SELECT * FROM shift
WHERE id = $_GET[shift]";
$hasil2 = mysqli_query($koneksi,$sql2);
$row2 = mysqli_fetch_assoc($hasil2);
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php';
});
});
</script>
<h1> Konfirmasi Pemesanan Ruang <?php echo $row['kode']; ?></h1><br>
<form class="form-horizontal" action="process/process-order-ruang.php" method="post">
<div class="form-group">
<label for="inputNamaPemesan" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<input type="text" name="nama_pemesan" class="form-control" id="typeahead" placeholder="Nama Pemesan">
</div>
</div>
<div class="form-group">
<label for="inputKeperluan" class="col-sm-2 control-label">Keperluan</label>
<div class="col-sm-10">
<select name="keperluan" class="form-control" id="inputKeperluan">
<option value="Diskusi Belajar">Diskusi Belajar</option>
<option value="Diskusi Tugas">Diskusi Tugas</option>
<option value="Dokumentasi">Dokumentasi</option>
<option value="Lain-lain">Lain-lain</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputWaktu" class="col-sm-2 control-label">Waktu</label>
<div class="col-sm-10">
<input type="text" class="col-sm-5" name="waktu" value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int; ?>:00" disabled> - <input type="text" class="col-sm-5"value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int+2; ?>:00" disabled>
</div>
</div>
<?php $shift = $_GET['shift'];
$ruangan = $_GET['id'];?>
<input type="hidden" value="<?php $int2 = (int)$shift;?>" name="shift">
<input type="hidden" value="<?php $int3 = (int)$ruangan;?>" name="ruangan">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Pesan</button>
</div>
</div>
</form>
and here is my code which should return json data from my table
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//connect with the database
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $koneksi->query("SELECT * FROM user
WHERE nama LIKE '%".$searchTerm."%' ORDER BY nama ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['nama'];
}
//return json data
echo json_encode($data);
?>
Any help would be much appreciated. Thanks a lot!

Use below code in script. remove semicolon from source. You can use colon for other parameters.
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php'
});
});
</script>

Related

Call out value into input field in PHP

How to display SQL result into text input?
When I press the generate button it should appear in the input text.
<?php
$random_name = "";
$conn = mysqli_connect("localhost","root","","wordlist");
if(!$conn)
{
die("Connection Error!");
}
$query_random = "SELECT kata FROM list ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn,$query_random);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$random_name = $row["kata"];
}
}
mysqli_close($conn);
?>
</head>
<body>
<div class="container" >
<form action="#">
<h4>Word Generator : </h4>
<div class="form-group">
<input type="text" class="form-control">
</div><br>
<button id="generate-btn" type="submit" title="Generate Word">Generate</button>
</div>
</form>
You just need to add this in place of your input, your code is correct but you missed to print the value, that's all
<input type="text" class="form-control" value="<?php echo #$random_name ?>">

Date is being sent as 0000-00-00 and returned as 11/30/-0001 when I use SQL update statement

For some reason when I edit the the date it's being sent as 0000-00-00 to the database. The wrest of the update is working as expected. I have the db rows for the dates set on type: date, default: none, and null: no.
Also tried to remove the values for the date inputs, that didn't do anything either. Please help, thank you!
<?php
include 'db.php';
$WAGE = 14;
$TAX = 0.01;
$SS = 0.062;
$MEDI = 0.0145;
$GOAL = 0.75;
if($_SERVER['REQUEST_METHOD'] === "POST") {
// Variables
$id = htmlspecialchars($_POST['id']);
$begDate = htmlspecialchars($_POST['date1']);
$endDate = htmlspecialchars($_POST['date2']);
$hours = htmlspecialchars($_POST['hours']);
$total = number_format($hours * $WAGE, 2, '.', '');
$taxDeducted = number_format($total * $TAX, 2,'.', '');
$SSDeducted = number_format($total * $SS, '2', '.', '');
$MEDIDeducted = number_format($total * $MEDI, '2', '.', '');
$deducted = number_format($taxDeducted + $MEDIDeducted + $SSDeducted, 2, '.', '');
$total -= number_format($deducted, 2, '.', '');
$save = number_format($GOAL * $total, 2, '.', '');
$date = $_POST['date1'];
// SQL
$sql = "UPDATE hours SET begDate=$date, endDate=$endDate, hours=$hours, deducted=$deducted, save=$save, total=$total WHERE id=$id;";
// EXECUTE
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
<?php
include 'header.php';
include 'db.php';
if(isset($_GET['id'])) :
$id = $_GET['id'];
$sql = "SELECT * FROM hours WHERE id=$id;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $res) :
$begDate = $res['begDate'];
$endDate = $res['endDate'];
$hours = $res['hours'];
endforeach;
?>
<div class="container form bg-light p-5">
<h1 class="text-center my-5">Add a week</h1>
<form action="editForm.php" method="post">
<input type="hidden" name="id" value="<?= $id; ?>" id="id">
<div class="row">
<div class="form-group col-md-5">
<input type="date" name="date1" id="date1" value="<?=$begDate;?>" class="form-control" required>
</div>
<div class="col-md-2 text-center">
<h3>TO</h3>
</div>
<div class="col-md-5 form-group">
<input type="date" name="date2" id="date2" value="<?=$endDate;?>" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-md-3 form-group mx-auto mt-5">
<input class="form-control" value="<?= $hours;?>" type="float" name="hours" id="hours" placeholder="Hours this period" required>
</div>
</div>
<div class="row text-center mt-5">
<div class="form-group col-md-3 mx-auto">
<input type="submit" value="SUBMIT" name="submit" class="btn btn-secondary">
</div>
</div>
</form>
</div>
<?php endif; ?>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'editForm.php',
method: 'post',
data: $('form').serialize()
})
.done(function(res, status) {
if(status == 'success') {
window.location.href = 'index.php';
}
})
.fail(function(res, status) {
if(status == 'error') {
console.log('error');
}
});
})
</script>
<?php include 'footer.php'; ?>

PHP Form update without logout

As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya

how update value input form class result

I Have a profile page and admin can edit profile users,
all process on one page done,How i can refresh and update value form data after success query update ?
User.class file :
class User {
...
public function updateUser($id, $firstname, $lastname, $phone, $birthday, $managerid)
{
$con = $this->DBconnect();
$id = (int)$id;
$managerid = $this->checkParam($managerid);
$firstname = $firstname;
$lastname = $lastname;;
$mobile = $phone;
$birthday = $this->checkParam($birthday);
$query = "UPDATE `users` SET `manager_id` = :manager_id,`firstname` = :firstname,`lastname` = :lastname,`birthday` = :birthday,`mobile` = :mobile WHERE `id` = :id";
$result = $con->prepare($query);
$result->BindParam(':id', $id, PDO::PARAM_INT);
$result->BindParam(':manager_id', $managerid, PDO::PARAM_INT);
$result->BindParam(':firstname', $firstname);
$result->BindParam(':lastname', $lastname);
$result->BindParam(':birthday', $birthday);
$result->BindParam(':mobile', $mobile);
$check = $result->execute();
return true;
}}
profile.php file :
<?php
if (isset($_GET['id'])) {
$id = (int)$_GET['id'];
}
$user = new User();
$user_info = $user->getuser($id);
while ($info = $user_info->fetch(PDO::FETCH_ASSOC)) {
$firstname = $info['firstname'];
$lastname = $info['lastname'];
$mobile = $info['mobile'];
$birthday = $info['birthday'];
$managerid = $info['manager_id'];
}
$manager_ob = new Manager();
$managers = $manager_ob->getAllManager();
$managers_name = array();
while ($manager = $managers->fetch(PDO::FETCH_ASSOC)) {
$managers_list[] = $manager;
}
if (isset($_POST['edit-profile'])) {
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
}
?>
<form method="post" action="#" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">ID</label>
<div class="col-sm-10"><input type="text" readonly class="form-control" name="user_id" id="user_id" value="<?php echo check_param($id); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_firstname" value="<?php echo check_param($firstname); ?>" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_lastname" value="<?php echo check_param($lastname); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10"><input type="text" class="form-control" name="user_mobile" value="<?php echo check_param($mobile); ?>"/></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label" for="birthday">Birthday
</label>
<div class="col-sm-10"><input id="birthday" type="text" class="form-control" name="user_birthday"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Manager</label>
<div class="col-sm-10"><select class="form-control m-b" name="manager_id">
<?php foreach ($managers_list as $managers_n) { ?>
<option <?php if ($managers_n['id'] == $managerid) {
echo 'selected';
} ?>
value="<?php echo $managers_n['id']; ?>"> <?php echo $managers_n['name']; ?></option>;
<?php }
?>
</select>
</div>
</div>
<input type="submit" name="edit-profile" class="btn btn-block btn-w-m btn-success"
value="Edit profile">
</form>
i load profile data after submit edit :
$update_result = $user->updateUser($_POST['user_id'],$_POST['user_firstname'],$_POST['user_lastname'],$_POST['user_mobile'],$_POST['user_birthday'],$_POST['manager_id']);
if($update_result){
echo 'Profile Edited';
}
only display message Profile Edited but must be refresh page for renew data
I must fetch again query for update values? or have better way ?
I suggest you use Ajax for this this is probably the best way to change the data without refreshing. More info about (jQuery) ajax http://api.jquery.com/jquery.ajax/
Your other option is to force a refresh after the submit. You can do this in PHP like so:
Header('Location: '.$_SERVER['PHP_SELF']);
I would suggest choosing ajax to tackle this problem though.
Good luck :)

Updation not working using pdo in php

I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];

Categories