php string comparison search only returning one entry not returning correct entries - javascript

I'm using ajax to send a search string to a php script that executes a mysql like function to find all related entries with the username like the string being sent for friend searching. I have two current entries in the database zukeru and zukeru2. when i search z i only get zukeru returned in my console output. When i search 2 i still get zukeru and im really not sure why.
Also how to i remove a specific field from a php nested tupple. I don't want to include the password field for obvious reason. Sorry im new to php learning as i go so far its not as bad as I thought it would be kinda similar to python.
returned object when searching the number 2, but i get zukeru and not zukeru2 doesn't make sense.
Object {0: "2", 1: "you wish you could see", 2: "zukeru", 3: "deleted for security", 4: "grant", id: "2", email: "deleted for security", username: "zukeru", password: "deleted for security", name: "grant"}
this is the search string i used for the above result. You can see i searched 2 and got back zukeru and not zukeru2
profile.php:92 searchstring=2
<?php
$db = new mysqli(security reasons removed.);
extract($_POST);
//I think i can remove this session start ?
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=mysqli_fetch_array($fetch);
//echo $search_string
echo json_encode($friends);
?>
Here is my jquery incase you wanted to see
function search(){
var url = "search_friends.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_friends").serialize(), // serializes the form's elements.
success: function(data)
{
//console.log(data);
var returned_friends = JSON.parse(data);
var html_built = '<br>';
console.log(returned_friends);
console.log($("#search_friends").serialize());
if (returned_friends){
$.each( returned_friends, function( key, value ) {
if (key =="username"){
html_built += '<li><a href="#"><button class="btn btn-primary" style="width:100%;" id="'+value+'" onClick="add_friend(this.id)"> Send '+value+' A Friend Request</button></li>';
}
});
}
html_built += ""
document.getElementById("list_friends").innerHTML = html_built;
}
});
return false;
}
this is what im currently using and I get undefined method. It cant find fetch_all(); and im using php 5.4
here is the console error returned.
<br />
<b>Fatal error</b>: Call to undefined method mysqli_result::fetch_all() in <b>/home/gzukel/public_html/search_friends.php</b> on line <b>7</b><br />
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends=$fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
?>

so something like this?
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=[]
while($row = $fetch->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
array_push($friends,$row['username']);
}
//echo $search_string
echo json_encode($friends);
?>

You Could use fetch all:
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends= $fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}

Related

Alert is showing but data is not updating and not able to click ok button of alert

My Alert is showing that updated successfully but data is not updating in database and not able to click ok button of alert. Here is my php code for upresult.php. Hope This will b helpful. Thank you in advance
my jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:formData,
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
You want to alert alert. Try with editing your flow control structure like this:
<?php
include("connection.php");
// you need to validate this data before sending it to update query
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
// this parameters should be binded to avoid SQL injection
$query = "
update stud
set
stud_name = '$name',
mobile = '$mob',
dob = '$dob',
address = '$add',
gender = '$gen',
country = '$cn',
state = '$st',
city = '$ct'
where stud_no = '$no';
";
/** This may be query for checking.
* Just execute it after first query and grab response from it.
* Depends of response you will return appropirate text message.
*/
$checkUpdateQuery = "
select if(count(*) = 1, true, false) as response
from stud
where stud_name = '$name',
and mobile = '$mob',
and dob = '$dob',
and address = '$add',
and gender = '$gen',
and country = '$cn',
and state = '$st',
and city = '$ct'
and stud_no = '$no';
";
/** mysqli_query will return false only if some error occurred.
* In other cases you will get true,
* so you need to check if data is updated by another query.
*/
$data = mysqli_query($conn, $query);
echo $data ? 'Updated Successfully' : 'Cannot update record';
Few things you should consider is do you have certain stud_no in database, mysqli_query returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
If you want we can change this query. Can you use PDO instead of mysqli?

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
$answerPoint = intval($_GET['radiobtn']);
$qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$lastid = $connect->insert_id;
if($lastid>0) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}
}
?>
I think that the problem may lie in the row where: if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) { ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function goBack() {
window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
if($('.radiobtn').is(':checked')) {
var radiobtn = $('.radiobtn:checked').val();
var qid = $('#qid').val();
var answer = $('input[name=answer1]:radio').val();
$.ajax(
{
type: "GET",
url: 'test.php',
dataType: "json",
data: "radiobtn="+radiobtn+"&qid="+qid,
success: function (response) {
if(response.status == true){
alert('points added');
}
else{
alert('points not added');
}
}
});
return false;
}
});
});
</script>
</body>
The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?
First, your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),
Second, I'd suggest using POST instead of GET:
type: "POST",
which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;
Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
console.log('here');
UPDATE:
Fourth: You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",
After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];
That should return the correct last insert id, if that was where your error was occurring.
mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id, because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.
if($connect->query($sql2)) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}

POST session variables to a relational database with ajax

I am trying to add some data to a relational database, and would like the session_user_id to be the foreign key for that database. When a user clicks a button, I want to make a database entry with the session_user_id and some other information I have POSTed to the page. My ajax posts to the php webpage page which it is run on (meaning all my scripts are on the same page)
I am currently getting a Uncaught ReferenceError: $sess_user_id1 is not defined. The jquery is firing. While I would love to get the undefined variable fixed, overall this does not seem like a very direct way to to this, and has added a bunch of confusing variables, when all the variables I need were already in my PHP statement. Is there any way to trigger the PHP entry without going through ajax and having to define the variables again?
Here is my php, which is at the header which is on the same page as my JS and HTML:
<?php
$markerid = $_POST["id"];
$name = $_POST["name"];
$type = $_POST["type"];
$point = $_POST["point"];
$lat2 = $_POST["lat"];
$lng2 = $_POST["lng"];
$locationdescription = $_POST["locationdescription"];
$locationsdirections = $_POST["locationdirections"];
session_start();
if (!isset($_SESSION['sess_user_id']) || empty($_SESSION['sess_user_id'])) {
// redirect to your login page
exit();
}
$sess_user_id1 = $_SESSION['sess_user_id'];
if ((isset($_POST['usid'])) && (isset($_POST['usid']))) {
$user_id_follow = strip_tags($_POST['usid']);
echo $user_id_follow;
$query = "INSERT INTO markerfollowing ( userID, markerID, type )
VALUES ('$user_id_follow', '$markerid', '$type');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close();
}
?>
Here is the HTML button:
<div class="btn pull-right">
<button class="btn btn-large btn-followmarker" type="submit"id="followmarker">Add me to the list</button>
</div>
Here is the jquery/ajax post:
<script/javascript>
$(document).ready(function () {
$("#followmarker").click(function(){
$.ajax({
type: "POST",
url: "", //
data: { usid: <?php echo '$sess_user_id1'; ?>},
success: function(msg){
alert("success");
$("#thanks").html(msg);
},
error: function(){
alert("failure");
}
});
});
});
</script
A sincere thanks for any and all help. I haven't worked with relational databases before.
<?php echo '$sess_user_id1'; ?>
is wrong. If you wont to get
data: { usid: 123} at $sess_user_id1 is 123, you should write
data: { usid: <?php echo "$sess_user_id1"; ?>}
See your html source code in your brawser. I think there is data: { usid: $sess_user_id1}, and javascript is not understand what is the $sess_user_id1
This is the only one problem that I can see now, but I don't understand your current task whole to say more.

Categories

Resources