PHP Update MySQL DB with AJAX call isn't doing anything - php

I'm trying to update a field on my database with PHP and AJAX
I have tested and found that the correct data is being sent, but the PHP that is handling the update is not working correctly.
All that happens is that I get the else response in conditional.
I need to update the DB depending on what the user input is.
Like I said, all I get for the response is the else response.
$youruname = $_POST['youruname'];
$selectedplayer = $_POST['selectedplayer'];
$selPlayerUname = $_POST['selPlayerUname'];
$flag = "";
$itStatus = "";
$checkit = mysqli_query($conn,"SELECT it FROM login WHERE uname='$selPlayerUname'");
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
}
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));
mysqli_free_result($checkit);
mysqli_close($conn);

There is something confusing here. You have a loop and after loop conditionals. Shouldnt your update query be inside a loop like:
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
}
Your $iStatus gets the last value from the database since its in the loop and then you check in conditionals
If above does not help then check your $_POST values to see if any of them are blank or null and do the query on PHPMyAdmin see if it actually returns anything.

mysqli_query requires you to pass the connection.
I wasn't doin that.
When I passed the values to the query directly, I figured it out.
Thank you very much for the help everyone

Related

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

display data from phpmyadmin

I'm a beginner in PHP5 and I'would like to have some help to get the code correct. Check the code and I'will be grateful for your support.
index.php:
if ($tag == 'AfficherMesAnnonce')
{
$Id_Utilisateur= $_GET['Id_Utilisateur'];
$annonce = $db->MesAnnonces($Id_Utilisateur);
if ($annonce)
{
$response["success"] = 1;
$response["annonce"]["Departure_place"] =$annonce["Departure_place"];
$response["annonce"]["Departure_date"] = $annonce["Departure_date"];
$response["annonce"]["Arrival_place"] = $annonce["Arrival_place"];
$response["annonce"]["Path_type"] = $annonce["Path_type"];
echo json_encode($response);
// annonce stored successfully
}else
{
$response["error_msg"] ="No annonce found";
return false;
echo json_encode($response);
}
}
DB_Function.php:
public function MesAnnonces($Id_Utilisateur)
{
$result = mysql_query("SELECT * FROM annonce WHERE Utilisateur_Id_Utilisateur = $Id_Utilisateur") or die(mysql_error());
// check for result
while($row = mysql_fetch_assoc($result))
{
$dd[]=$row;
}
$response=array('annonce'=> $dd);
return $response;
}
and thank you in advance.
You DB function is creating the dd array as a collection of rows, and then nesting that as an element of what's returned. But in your calling script you're assigning
$response["annonce"]["Departure_place"] = $annonce["Departure_place"]
--but the right side of that doesn't exist. You could instead assign:
$response["annonce"]["Departure_place"] = $annonce[0][0]["Departure_place"]
which would be the first row. You're not iterating through the rows in the client script, or using any kind of index to select a row.

PHP MYSQL compare database value to POST value

This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows

Query only returns one result when using php but works on raw SQL

I am dying here :-) Please help out!
The following query gets different messages for different users from the same table based on current time.
$message = mysql_query("SELECT * FROM `table`
WHERE `Scheduled` <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 MINUTE)
AND `Status` != 'published'");
/** Kill db connection and exit script if no results are found **/
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
{
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}
}
This only echos the first account, please help I have a headache. I have run this on the db directly and it works fine. I believe I am messing up in php
I think you are getting non associative array. If you wanna assoc. array, you have to change it :
while ($row = mysql_fetch_array($message))
to
while ($row = mysql_fetch_assoc($message))
//you have made a drastic mistake in your code check now it will work
if (mysql_num_rows($message)== 0) {
mysql_close($db) && exit();
}
else {
while ($row = mysql_fetch_array($message))
{
$msg = $row["Messages"];
$accnt = $row["Account"];
if ($accnt == 'Account1')
echo $msg.$accnt;
elseif ($accnt == 'Account2')
echo $msg.$accnt;
else
echo "Nothing Here!";
}
}

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