How to check whether a text variable is equal to an Array - php

My requirement is to check whether a text variable is equal or not to an mysql output array.
The mysql output array I have taken as follows,
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$('#book_name').val()=$book_required;
if(in_array($book_required,$avail_books))
{
alert("Not Available");
}
else{
$.ajax({
url:"books.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
}
}
But this is not working. Can someone show where I have messed this?

There can be other ways to accomplish what you want.
For example, use the following query:
SELECT count(*) FROM takenbooks where book_name = ?
But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believe is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)
For the HTML
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: 'checkdata.php',
data: {data1: $('#book_name').val()},
success: function(data){
alert(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
})
})
</script>
For the PHP (checkdata.php)
<?php
if (isset($_POST["data1"])){
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
if(in_array($_POST["data1"],$avail_books)) {
echo "Not Available";
} else {
// Place insert query here
echo "New Record inserted";
}
}
?>

You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)
<?php
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
Book name: <input type="text" name="book_name">
<input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>
const avail_books = <?php json_encode($avail_books); ?>;
document.querySelector('#insert_form').addEventListener(function (evt) {
evt.preventDefault();
let book_name = evt.target.book_name.value;
let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
document.querySelector('#available').innerHTML = book_name + " is " + not_available + " available.";
});
</script>
</body>
</html>
PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.
Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:
const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];
With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.

It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.
<html>
<body>
<form action="" method="POST">
<input type="text" name"book" required placeholder="Type the name of the Book" />
<input type="submit" value="Search Book" />
</form>
<div><h2>Results:</h2>
<?php
if(isset($_POST['book'] && !empty($_POST['book'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli("localhost", "root", "", "newbooks");
$stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
$stmt->bind_param("s", "%" + $_POST['book'] + "%");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
}
}
?>
</div>
</body>
</html>

Related

jQuery function doesn't update data when it is updated in the database

I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.

Getting value from database using jquery on change event

I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>
Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS
Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.

MySQLI how to insert a form into database by language select

Im having an issue with form method.
How can I insert a form value in the database in different table by language select.
I have in my database the tables called article_en / articles_ro ,and when I chose with select english I want the values to be inserted in the article_en
Also when I select the language its not staying selected.
And if I write something in the inputs and chose a language the inputs are being cleared.
PS:Im a newby , I am still learning.
This is the language select code
<?php
define("LANG",$_GET['lang']);
include('../db.php');
function select_langs(){
global $conn;
echo'<h2 class="box-title">Select the language where you want to the article</h2>
<select id="select_language">
<option selected disabled hidden value=""></option>';
$get_languages = mysqli_query($conn, "SELECT lang,title from `languages`") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($get_languages)){
if($row['title'] == $_GET['lang']){
echo'<option value="insert_article.php?lang='.$row['lang'].'" selected>'.$row['title'].'</option>';
}
else{
echo'<option value="insert_article.php?lang='.$row['lang'].'">'.$row['title'].'</option>';
}
}
echo'</select>';
}
?>
And this is the insert code.
<?php
include('./lang.php');
include('../db.php');
define("LANG",$_GET['lang']);
select_langs();
// extract data from form; store in variable
$title = $_GET['title'];
$link = $_GET['link'];
if (!empty($title) and !empty($link ) and !empty($_GET['lang'])) {
// Define the query to inser the song request
$sql = "INSERT INTO `articles_".LANG."`(title , link)VALUES (".$title.", ".$link.")";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#select_language").bind("change",function(){var n=$(this).val();return""!=n&&(window.location=n),!1});
</script>
<form action="insert_article.php" method="get">
<label id="first">title:</label><br/>
<input type="text" name="title"><br/>
<label id="first">link:</label><br/>
<input type="text" name="link"><br/>
<input type="submit" value="submit">
</form>
Thank You.
I think you need to use ajax to send the details to the php to insert it in your database. It's just easier.
var select_language= document.getElementById("select_language").value;
var title= document.getElementById("title").value;
var link= document.getElementById("link").value;
var data= {select_language: select_language,title: title,link:link};
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function(html)
{
console.log (html);
alert("Success");
},
error: function (html)
{
console.log (html);
alert("Failure");
}
});
insert.php
include '../dbconfig.php';
$select_language= mysqli_real_escape_string($db,$_POST['select_language']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$link= mysqli_real_escape_string($db,$_POST['link']);
$query = "your insert query";
mysqli_query($db, $query) or die(mysqli_error($db));
Hope this helps.

HTML Button not Submitting Every Time

Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});

Check if cell number exists in database

i want to check if the cell number a user is trying to enter already exists.
But the code below always calls this "Cell Number in use",
what im i doing wrong? Still starting with php.
<?php
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
This should work:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' LIMIT 1");
$find=mysql_num_rows($query);
die($find);
}
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
So if you send "data" to the script it'll look for results, output the count, and exit.
If not, it'll display the rest of the page.
Also note how I put a LIMIT 1 there, just a little performance optimization, since you only want to know if the data is there or not.
Edit: This is a better approach in terms of performance and security:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query = mysql_query("SELECT COUNT(*) AS number from users where cell='".mysql_real_escape_string($cell)."' LIMIT 1");
$find = mysql_result($query, 0);
die($find);
}
?>
I see your post url is:
url:"formpost"
if js code and the php in the same file, the return data of ajax will be whole html and javascript instead of just "echo $find;"; of course your data will never be 0;
First thing to do is to see what is the value of data returned. That will give you some idea where the problem is. Also, it is better to use count() than to get all rows just so you can do mysql_num_rows().
SELECT COUNT(*) from users where cell='$cell'
will return the number of rows with cell that equals $cell. Interpret that result and then echo what you need. Also check if query was successful (handle errors). If the $_POST['cell'] is not set there is no reason to query the database for cell number that is null, just return desired value immediately. You also got comments that you are vulnerable to sql injections so you should consider fixing that too.
if you are receiving the result from the same page in your ajax call its as if you have browsed to the page so the returned content will include everything on the page including your javascript. Try either using a different page as the ajax target or doing somthing like this:
<?php
if(isset($_POST["cell"]))
{
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
}
else
{
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
<?php } ?>
Which should mean that the javascript is only written out if you dont have a post value.

Categories