How to send multiple json response in php back to ajax - php

<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
if($res) {
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['success']=true;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
$re = array();
while ($row = mysqli_fetch_assoc($query))
{
print_r($row);
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
This is my full PHP code in this I need two json responses,
1> when I refresh the page
$sql="call regtask2('$userid')";
This query has to work and pass the response to the ajax, then I am using click button. When I use click button this query has to work and pass the response
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
I this is poosible?

3 options:
Just split your php code. On refresh, load script1.php and for your other ajax call, load script2.php.
You will need to set identifiers for your calls. In your ajax, add an "is_submit=true" to the query. In your php, check that value.
Assign your return value to $return and return that.

It's simple just add second query result to your previous json !, also consider adding some validation into user input to prevent sql injection
getting userid from $_POST is really bad idea
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
$re = array();
if($res) {
$re['success']=true;
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
while ($row = mysqli_fetch_assoc($query))
{
$re['userObj'][]=$row;
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>

Related

PHP foreach echo prints “Symbols” as value

I fetched data dynamically from from MySQL using a drop down menu through Ajax which was successful but when I echo the array values, instead of giving me the list of emails it was showing just symbols.
Take a look at the image below:
From the Email List, those are the symbols that were echo out.
here is my php code
if(isset($_POST["confirm_no"])){
$d = $_POST['confirm_no'];
$query = mysqli_query($mysqli, "select * from jobseeker WHERE confirm_no LIKE '$d%'");
//Display list
if(mysqli_num_rows($query) > 0){
$row = mysqli_fetch_array($query);
foreach ($row as $r) {
$emailArr[] = $r["mails"];
}
$emails = implode(";", $emailArr);
echo $emails;
}else{
echo 'No email for this selection.';
}
}
And the jQuery
$(document).ready(function(){
$('#smode').change(function(){
var confirm_no = $(this).val();
$.ajax({
type:'POST',
data:"confirm_no="+confirm_no,
url:'get_email.php',
success:function(data){
$('#emaillist').val(data);
}
});
});
});
Why is it echoing out this symbols?
Rebuild your code as:
//Display list
if(mysqli_num_rows($query) > 0){
// You have many results - fetch them all iteratively
// use `fetch_assoc` to have ability to use `mails`
while ($row = mysqli_fetch_assoc($query)) {
$emailArr[] = $row["mails"];
}
$emails = implode(";", $emailArr);
echo $emails;
}else{
echo 'No email for this selection.';
}
You are fetching the data incorrectly, you only fetch the one row (the call to mysqli_fetch_array()
$row = mysqli_fetch_array($query);
foreach ($row as $r) {
$emailArr[] = $r["mails"];
}
Could be better written as
while( $row = mysqli_fetch_assoc($query)) {
$emailArr[] = $row["mails"];
}
Or...
$emailArr = mysqli_fetch_all($query, MYSQLI_ASSOC);
$emailArr = array_column($emailArr, "mails");

PHP Script does not echo json encoded array

I have a php script which should echo a bunch of datasets in a json encoded string. Though the page is blank.
<?php
$con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE");
if(!$sql = "SELECT news.title, news.content, login.username, news.id, news.date, news.timestamp, news.importance, news.version FROM news INNER JOIN login ON news.id = login.id ORDER BY timestamp DESC") {
echo "FAIL";
}
mysqli_query($con,$sql);
$res = mysqli_query($con,$sql);
$result = array();
while($row = $res->fetch_array())
{
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(["result"=>$result]);
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
What is the problem here? I tried some error detection with if(!..) but it did not help. I think the problem may be the array creation and/or echo, though I cannot figure out how to fix that.
You should check the result of json_encode, since you are encoding data that comes from the database you might have some stuff that requires escaping.
$json = json_encode(...);
if ($json === false) {
echo "Error = " . json_last_error() . " " . json_last_error_msg();
// You may want to var_dump the $result var here to figure out what the problem is
} else {
echo $json; // Should be ok
}

Fail to update the data in database

I try to update the data in the database, but when I run the code, there is no error message appear, looks like its a logical error but I still don't have any clue about what is happening with my code.
Here is the code
<?php
include("conn.php");
SESSION_START();
if($_SESSION["loggedin"]!="true"&& $_SESSION['login'] != '')
header("location:login.php");
$aid = $_SESSION["usr"];
$result = mysql_query("select r.CustomerID from customer c inner join results r on r.CustomerID = c.CustomerID where c.Username = '".$aid."' ");
if (false === $result) {
echo mysql_error();
}
$row = mysql_fetch_assoc($result);
?>
<?php
if (isset($_POST["submitbtn"]))
{
$bookid = $_POST["bookid"];
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
$query = mysql_query("UPDATE `results` SET LP = '$LP', budget = '$budget', SmokeP = '$smokep', sp_req = '$spreq'
WHERE results.BookID = '".$bookid."' and results.CustomerID = '".$result."'");
if (false === $query)
{
echo mysql_error();
}
?>
<script type = "text/javascript">
alert("Amendment Saved!!");
</script>
<?php
}
?>
Is the error coming from the select query? Or the if statement for the submitbtn went wrong?
First of all you cant put session start here
You must put it on the first line after open php tag
Second
update res='$ new_value' where ...
Tell me if it's not usefull to try another solution

Array objects not being printed in input fields and sql query not receiving the id value

I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];

php mysql check previous row

I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php

Categories