Check if cell number exists in database - php

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.

Related

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

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>

AJAX not working, success function is working?

the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.

JQuery AJAX update a textbox on another textbox textchanged

I would like to update my input text type (id="textbox2") when i typed something at another input text type (id="textbox1").
Here's my initial code:
$("#textbox1").keyup(function(){
$.ajax({
type: "POST",
url: "idgetter.php",
data: 'id='+$("#textbox1").val(),
success: function(n) {
$('#textbox2').val(n);
},
error: function(n) {
$('#textbox2').val(n);
}
});
});
And my idgetter.php :
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) return "none";
else{
$r = mysql_fetch_array($q);
return $r["name"];
Long story short, this did not work, any idea why?
In idgetter.php, Instead of returning using return give
echo "none";
and
echo $r["name"];
You should try echo instead of return:
your code would be like this:
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) echo "none";
else{
$r = mysql_fetch_array($q);
echo $r["name"];
Think there are a few amends needed in your php:
change return to echo (like stated in the other answers)
change your if statement to
if(mysql_num_rows($q)==0){
echo 'none';
}else{
$r = mysql_fetch_assoc($q);
echo $r['name'];
}
That should do it hopefully. Also as an FYI its worth trying to avoid adding $_POST[''] items to SQL statements directly, as its prone to SQL injection breaches.

AJAX does not recognize json array

Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>
you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.
Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.
I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);

my post doesn't insert in my database

I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.

Categories