check duplicate rand function value in database and generate it again - javascript

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>

I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}

when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

Related

JavaScript , AJAX, PHP : trying to get values from $_POST

I am trying to build a way for a user to be able to create an article, if they want, with a button they can add an input for a text, a file input etc.
I want to send this form with JavaScript vanilla (training)
so what I do in my js is that I loop into my different added input then I append them to formData
and send this formData to my controller to treat it and add it to my database.
Problem is that by iterating my input when I append my input into formData I have to add the index
so when I send it and print_r my post
I get like:
text01
text02
text03 etc.
it would be fine if it was only these input that I wanted to send but in my post I have other inputs which are sent the same way so I get like
title01
paragraphe01
title02
paragprahe02
the problem will be when I want to query to add the data to my database I would have to bind all of these to my query, but of course I can't make 50 lines of
bind('text01', $text01)
I don't think it would be a nice way to do it
so I am looking for a way to be able to query all of these data I thought of maybe a way getting only the paragraphs indexes and putting them in an array containing only paragraphs then forEach() everything.
another array for another input etc. but I can't find a way to do it, is it even possible
so here is my code
<?php
include '../flash/Flash.php';
$pageTitle = "création d'article";
$css = "create_article";
include './assets/include/_header.php';
?>
<body>
<?php
include '../view/assets/include/_nav.php';
flash('createB');
?>
<main>
<form action="../controller/Crud_controller.php" method="post" class="form_container" enctype="multipart/form-data">
<input type="hidden" name="type" value="createB" id="type">
<h3 id="status"></h3>
<h5>titre du post</h5>
<input type="text" name="title" id="title">
<h5>Paragraphe</h5>
<textarea name="paragraphe" id="product_desc" cols="30" rows="10"></textarea>
<input type="file" id="img_livre" name="name" accept="image/png, image/jpeg">
<h5>Note 1</h5>
<input type="text" name="note" id="note">
<button type="button" data-prototype="" class="btn btn_primary btn-js">Ajouter un paragraphe ou une image ?</button>
<button type="button" class="btn btn_primary btn-js-ajax">envoyer</button>
</form>
</main>
</body>
<script>
const btnSubmit = document.querySelector('.btn-js-ajax');
btnSubmit.addEventListener('click', uploadFiles);
function uploadFiles() {
let formData = new FormData();
let images = document.getElementsByName('name');
let type = document.getElementById('type').value;
let paragraphe = document.getElementsByName('paragraphe');
let note = document.getElementsByName('note');
let title = document.getElementById('title').value;
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
formData.append('title', title);
formData.append('type',type );
const ajax = new XMLHttpRequest();
fetch("../controller/Crud_controller.php", {method: "POST", body: formData}).then(res => res.text()).then(data => {console.log(data);})
ajax.upload.addEventListener("load", completeHandler, false);
}
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key)]);
console.log(result);
const form = document.querySelector('.form_container');
const addBtn = document.querySelector('.btn-js');
function addInput() {
const paragraphe = document.createElement('textarea');
paragraphe.name = 'paragraphe';
paragraphe.style = "margin-top:100px";
paragraphe.cols = "30";
paragraphe.rows = "10";
const file = document.createElement('input');
file.type = 'file';
file.style = "border: none";
file.name = 'name';
file.accept = "image/png, image/jpeg";
const note = document.createElement('input');
note.type = 'text';
note.name = 'note';
const btnRemove = document.createElement('a');
btnRemove.className = 'btn_primary btn';
btnRemove.innerHTML = 'supprimer';
form.insertBefore(btnRemove, addBtn);
form.insertBefore(note, btnRemove);
form.insertBefore(file, note);
form.insertBefore(paragraphe, file);
}
addBtn.addEventListener('click', addInput);
</script>
</html>
here the controller getting the post ajax element
<?php
include '../model/CrudModel.php';
include '../model/Blog.php';
require_once '../flash/Flash.php';
class Products
{
private $crudModel;
private $crudBlog;
public function __construct()
{
$this->crudModel = new Product;
$this->crudBlog = new Blog;
}
public function blog()
{
$data = $_POST;
echo "<pre>";
print_r($data);
echo "</pre>";
print_r($_FILES);
if (empty($data['title']) || empty($data['paragraphe'])) {
flash('createB', 'remplir au moins le titre et le paragraphe et ajouter une image');
// header('Location: ../view/crud_blog.php');
} else {
forEach($data as $k => $v)
{if ($this->crudBlog->setBlogPost($data)) {
foreach ($_FILES as $file) {
if ($this->crudBlog->setBlogImages($file)) {
flash('createB', "c'est bon");
// header('Location: ../view/create_blog_page.php ');
}
}
}}
}
}
}
$init = new Products;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['type']) {
case 'crud':
$init->produit();
break;
case 'createB':
$init->blog();
break;
default:
echo "je peux pas";
break;
}
}
here is my Model where I have all my queries
<?php
require_once '../dbb/Database.php';
class Blog {
private $con;
private $table_name = "blog_post";
public function __construct()
{
$this->con = new Database;
}
public function setBlogPost($array) {
$query = "INSERT INTO " . $this->table_name . " SET title = :title , paragraphe=:p1 , note = :note1";
$this->con->prepare($query);
$this->con->bind('title' , $array['title']);
$this->con->bind('p1' , $array['paragrape']);
$this->con->bind('note1' , $array['note']);
if($this->con->execute()){
return true;
}return false;
}
public function setBlogImages($file){
$table_name = "blog_image";
$query = "INSERT INTO " . $table_name . " SET name = :img , id = LAST_INSERT_ID()";
$this->con->prepare($query);
$this->con->bind('img',$file['name']);
move_uploaded_file($file['tmp_name'], "../view/assets/uploads/".$file['name']);
if ($this->con->execute()){
return true;
}return false;
}
and this is the response I get in my console.log maybe it will be more clear
thank you
Little edit so i managed to make an array for each of my input
array paragraphe for paragraphes
note for notes etc...
i changed this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
by this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name[]" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe[]"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note[]" + i, notes);
}
}
but here's the problem
i can't find a way to foreach multiple array in php to add them to my database
this is the response result i get in my console now
reponse2

Multiple fields with the same name in AJAX and PHP

Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.
Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

Php variable if else statement

I am trying to define my php variable for my php poll vote. I want to echo "Have a good day!" if the vote in for "Hello" is more that "Others" else echo "Have a good night!". :
if ($votePercent < $votePercent) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
How to I define the variable $votePercent?
<div class="container">
<h3><?php echo $pollResult['poll']; ?></h3>
<p><b>Total Votes:</b> <?php echo $pollResult['total_votes']; ?></p>
<?php
if(!empty($pollResult['options'])){ $i=0;
//options bar color class array
$barColorArr = array('azure','emerald','violet','yellow','red');
//generate option bars with votes count
foreach($pollResult['options'] as $opt=>$vote){
//calculate vote percent
$votePercent = round(($vote/$pollResult['total_votes'])*100);
$votePercent = !empty($votePercent)?$votePercent.'%':'0%';
//define bar color class
if(!array_key_exists($i, $barColorArr)){
$i = 0;
}
$barColor = $barColorArr[$i];
?>
<div class="bar-main-container <?php echo $barColor; ?>">
<div class="txt"><?php echo $opt; ?></div>
<div class="wrap">
<div class="bar-percentage"><?php echo $votePercent; ?></div>
<div class="bar-container">
<div class="bar" style="width: <?php echo $votePercent; ?>;"></div>
</div>
</div>
</div>
<?php $i++; } } ?>
Back To Poll
</div>
This is the how I am connected to mysql.
<?php
class Poll{
private $dbHost = 'localhost';
private $dbUser = '';
private $dbPwd = '';
private $dbName = '';
private $db = false;
private $pollTbl = 'polls';
private $optTbl = 'poll_options';
private $voteTbl = 'poll_votes';
public function __construct(){
if(!$this->db){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUser, $this->dbPwd, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Runs query to the database
* #param string SQL
* #param string count, single, all
*/
private function getQuery($sql,$returnType = ''){
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
}
return !empty($data)?$data:false;
}
/*
* Get polls data
* Returns single or multiple poll data with respective options
* #param string single, all
*/
public function getPolls($pollType = 'single'){
$pollData = array();
$sql = "SELECT * FROM ".$this->pollTbl." WHERE status = '1' ORDER BY created DESC";
$pollResult = $this->getQuery($sql, $pollType);
if(!empty($pollResult)){
if($pollType == 'single'){
$pollData['poll'] = $pollResult;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$pollResult['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData['options'] = $optionResult;
}else{
$i = 0;
foreach($pollResult as $prow){
$pollData[$i]['poll'] = $prow;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$prow['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData[$i]['options'] = $optionResult;
}
}
}
return !empty($pollData)?$pollData:false;
}
/*
* Submit vote
* #param array of poll option data
*/
public function vote($data = array()){
if(!isset($data['poll_id']) || !isset($data['poll_option_id']) || isset($_COOKIE[$data['poll_id']])){
return false;
}else{
$sql = "SELECT * FROM ".$this->voteTbl." WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$preVote = $this->getQuery($sql, 'count');
if($preVote > 0){
$query = "UPDATE ".$this->voteTbl." SET vote_count = vote_count+1 WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$update = $this->db->query($query);
}else{
$query = "INSERT INTO ".$this->voteTbl." (poll_id,poll_option_id,vote_count) VALUES (".$data['poll_id'].",".$data['poll_option_id'].",1)";
$insert = $this->db->query($query);
}
return true;
}
}
/*
* Get poll result
* #param poll ID
*/
public function getResult($pollID){
$resultData = array();
if(!empty($pollID)){
$sql = "SELECT p.subject, SUM(v.vote_count) as total_votes FROM ".$this->voteTbl." as v LEFT JOIN ".$this->pollTbl." as p ON p.id = v.poll_id WHERE poll_id = ".$pollID;
$pollResult = $this->getQuery($sql,'single');
if(!empty($pollResult)){
$resultData['poll'] = $pollResult['subject'];
$resultData['total_votes'] = $pollResult['total_votes'];
$sql2 = "SELECT o.id, o.name, v.vote_count FROM ".$this->optTbl." as o LEFT JOIN ".$this->voteTbl." as v ON v.poll_option_id = o.id WHERE o.poll_id = ".$pollID;
$optResult = $this->getQuery($sql2);
if(!empty($optResult)){
foreach($optResult as $orow){
$resultData['options'][$orow['name']] = $orow['vote_count'];
}
}
}
}
return !empty($resultData)?$resultData:false;
}
}
This is the index.php code.
<form method="post" action="">
<h3><?php echo $pollData['poll']['subject']; ?></h3>
<ul>
<?php foreach($pollData['options'] as $opt){
echo '<li><input type="radio" name="voteOpt" value="'.$opt['id'].'" >'.$opt['name'].'</li>';
} ?>
</ul>
<input type="hidden" name="pollID" value="<?php echo $pollData['poll']['id']; ?>">
<input type="submit" name="voteSubmit" value="Vote">
Results
</form>
This is my test url: php poll. Please let me know if you need more details. I am not sure which code is needed to be shown here. Thankyou so much for helping.
Try this --
results.php
if ($_GET['PollID'] == 2) {
$votePercent = "Have a good day!";
} else {
$votePercent = "Have a good night!";
}
index.php
In this page, radio button value are 1 and 2

How to enable disable option value in select based on condition PHP

After user select location,in the next select option which is select car, will show list of car in selected location..The list of car retrieved direct from database..So i need to display all the car list in that area and need to disable enable the car list according the condition which is if the car id is not available the option value will disabled..and the option value become enable if car id is available..
<?php
$car = "SELECT *,location_master.location_id , location_master.location_name,
appcarinfo.loc_id_ext, appcarinfo.location ,appcarinfo.model ,appcarinfo.noplat FROM location_master
INNER JOIN appcarinfo ON
appcarinfo.lat = location_master.gmaplat
AND
appcarinfo.lon = location_master.gmaplng
where appcarinfo.model='".$fetchres['idmodel']."' ";
$qcar = mysqli_query($conn, $car);
?>
<option disabled value="" selected hidden>Please Select Car</option>
<?php
while ($showcar= mysqli_fetch_array($qcar))
{
if ($showcar['car_id']=="Available")
{
?>
<option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" enabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
else
?> <option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" disabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
?>
</select>
SELECT OPTION
I'm also new to AJAX..how to pass data and retrieve it back to select option
//check availability car
function check_availability()
{
//id from form
var reservation1 = document.getElementById("reservation");
var pickup_date = document.getElementById("pickup_date").value;
var return_date = document.getElementById("return_date").value;
var pickup_time = document.getElementById("pickup_time").value;
var return_time = document.getElementById("return_time").value;
var carID= document.getElementById("carID").value;
$.ajax({
type : "POST",
url : "function/check_car_availability.php",
data : {
pickup_date : pickup_date,
return_date : return_date,
pickup_time : pickup_time,
return_time : return_time,
carID : carID,
},
dataType : "JSON",
success : function(data) {
$('#edt_pickup').val(data.edt_pickup);
$('#edt_return').val(data.edt_return);
$('#msgCheck').html(data.msgCheck);
$('#btn_proceed').html(data.btn_proceed);
}
});
}
check_car_availability.php
<?php
if ($_POST['pickup_date'])
{
$pickup_date = $_POST['pickup_date'];
$return_date = $_POST['return_date'];
$pickup_time = $_POST['pickup_time'];
$return_time = $_POST['return_time'];
$car_id = $_POST['car_id'];
$owner_id = $_POST['owner_id'];
//convert normal date to epoch
$pickup_date1 = explode("/",$pickup_date);
$return_date1 = explode("/",$return_date);
$pickup_time1 = explode(":",$pickup_time);
$return_time1 = explode(":",$return_time);
//hour, minute, second, month, day, year
$edt_pickup = mktime($pickup_time1[0],$pickup_time1[1],0,$pickup_date1[1],$pickup_date1[0],$pickup_date1[2]);
$edt_return = mktime($return_time1[0],$return_time1[1],0,$return_date1[1],$return_date1[0],$return_date1[2]);
//convert from d/m/Y to Y-m-d
$pickup_date_2 = $pickup_date1[2]."-".$pickup_date1[1]."-".$pickup_date1[0];
$return_date_2 = $return_date1[2]."-".$return_date1[1]."-".$return_date1[0];
//keluarkan tarikh yg customer pilih ada tak dlm booking master
$chkBooked = mysqli_query($conn, "SELECT count(car_id) AS countid FROM appbooking WHERE
((start_rent >= '$edt_pickup' AND end_rent <= '$edt_return')
OR (((start_rent <= '$edt_pickup' AND end_rent >= '$edt_return')))
OR (((end_rent >= '$edt_pickup' AND end_rent <= '$edt_return')))
OR (((start_rent >= '$edt_pickup' AND start_rent <= '$edt_return')))) AND car_id = '$car_id' AND status !='0'");
$fetchBooked = mysqli_fetch_array($chkBooked);
if($fetchBooked['countid'] != 0) //kalau ada show not available
{
$availability = "Not Available";
$available_count = 0;
} else //kalau tak de show available
{
$availability = "Available";
$available_count = 1;
}
//keluarkan car details
$carDetails = mysqli_query($conn, "SELECT * FROM appcarinfo WHERE car_id = '$car_id'");
$fetchchkowner = mysqli_fetch_array($carDetails);
//kalau manual availability check ada tak date dlm range yg owner dah set
$sql = mysqli_query($conn, "SELECT count(car_availability.availability_id) AS cntAvail FROM appcarinfo INNER JOIN car_availability ON car_availability.car_id = appcarinfo.car_id WHERE appcarinfo.car_id = '$car_id' AND car_availability.start_available <= '$edt_pickup' AND car_availability.end_available >= '$edt_return'");
$fetch = mysqli_fetch_array($sql);
if ($fetchchkowner['custom_availability'] == 1) //if owner set manual availability
{
if ($fetch['cntAvail'] > 0) //kalau ada
{
$avail = 1;
} else //kalau tak de
{
$avail = 0;
}
} else //if owner set auto availability
{
$avail = 1;
}
//check if this is klezcar car
if($fetchchkowner["owner_id"] == "0")
{
$klezcar_loc_id = $fetchchkowner["loc_id_ext"];
//check availability for blocked date klezcar
$sqlBlock = "SELECT * FROM `blocked_date_klezcar` where (
('".$pickup_date_2."' > startdate and '".$pickup_date_2."' < enddate)
or ('".$return_date_2."' > startdate and '".$return_date_2."' < enddate)
or ('".$pickup_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
or ('".$return_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
) and (location=0 or location=".$klezcar_loc_id.") order by location desc limit 1";
$queryBlock = mysqli_query($conn,$sqlBlock);
if(mysqli_num_rows($queryBlock) > 0)
{
$resBlock = mysqli_fetch_object($queryBlock);
$avail = 0;
$klezcar_blocked = 1;
$klezcar_blocked_reason = $resBlock->reason;
}
else
{
$klezcar_blocked = 0;
}
}
//calculation price rate
include 'calculation_price/calculationprice.php';
$encry = md5($edt_pickup.$edt_return.$total_pay.$total_rate.floor($day).$bhourplus.$car_id.$owner_id.$secretAuth);
//combine appbooking & car availability variable
if ($avail == 1 && $available_count == 1)
{
$availStatus = "<div class='alert alert-success'>You are good, car available.<br>Rental Price : Total <span style='font-size:20px; font-weight: bold;'>".number_format($total_pay,2)."</span> for ".floor($day)." day(s) ".$bhourplus." hour(s)</div>";
$btn_proceed = "<a href='confirmbooking.php?pickupdate=".$edt_pickup."&returndate=".$edt_return."&totalpay=".$total_pay."&totalrate=".$total_rate."&bookday=".floor($day)."&bookhour=".$bhourplus."&carid=".$car_id."&ownerid=".$owner_id."&encry=".$encry."' class='btn btn-primary'>Proceed</a>";
} else
{
$availStatus = "<div class='alert alert-danger'>We are sorry, car not available. Please refer Available & Not available date table.</div>";
$btn_proceed = "";
if($klezcar_blocked === 1)
{
$availStatus = "<div class='alert alert-danger'>".$klezcar_blocked_reason."</div>";
$btn_proceed = "";
}
}
/* *** SPECIAL FOR RAYA 2019 *** */
$start_blocked_date = "2019-06-04";
$end_blocked_date = "2019-06-09";
if( ($pickup_date_2 >= $start_blocked_date && $pickup_date_2 <= $end_blocked_date)
|| ($return_date_2 >= $start_blocked_date && $return_date_2 <= $end_blocked_date)
|| ($pickup_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date)
|| ($return_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date))
{
$availStatus = "<div class='alert alert-danger'>The date has been marked as Hari Raya Aidlifitri holiday session. We accept minimum rental of 7 days and above only. Please re-select date at least 3/6/2019 - 10/6/2019.</div>";
$btn_proceed = "";
}
/* *** SPECIAL FOR RAYA 2019 *** */
//return value
$data['edt_pickup'] = $edt_pickup;
$data['edt_return'] = $edt_return;
$data['msgCheck'] = $availStatus;
$data['btn_proceed'] = $btn_proceed;
$data['total_rate'] = $total_rate;
$data['total_pay'] = $total_pay;
$data['no_day_booking'] = floor($day);
$data['no_hour_booking'] = $bhourplus;
echo json_encode($data);
}
?>

How to add an array from the data attribute and id using javascript and combine them in array php?

I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}

Categories

Resources