I am trying to update status onclick. In display function i have given like this
if($row['IsActive']=="1")
{
echo "<td> <a href='managecategories.php?IsActive=0&CategoryID=" .$row['CategoryID']. "'>Active</a></td>";
}
else
{
echo "<td> <a href='managecategories.php?IsActive=1&CategoryID=" .$row['CategoryID']. "'>Deactive</a></td>";
}
and on loading the page it should get the database status, for that i have written code like this
if (isset($_GET['IsActive']))
{
$status = $_GET['IsActive'];
$id = $_GET['CategoryID'];
if($status =="0")
{
$sql = "update Categories set IsActive= 0 where CategoryID='$id'";
$result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error());
}
else
if($status =="1")
{
$sql = "update Categories set IsActive= 1 where CategoryID='$id'";
$result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error());
}
}
But i am not getting any result not errors... please hel me where i am wrong
I would assume that you are using an integer type in the database. I know I would use TINYINT for any boolean, because MySQL does not have a type boolean.
Your display function if($row['IsActive']=="1") supports that. However, your update query $sql = "update Categories set IsActive= 'false' where CategoryID='$id'"; does not. Here you try to save a string value.
So you should first make sure that the boolean value is stored as a TINYINT in the database. (Strings are harder to work with on the PHP side.) Then you need to make sure that the values you insert into the database are actually of the correct type. You should use 0 for false and 1 for true. That will also work in PHP:
$isActive = 1;
$if($isActive) {
// This code is run
}
Also note that you should validate the category id. You're now inserting user input without prior validation, which is dangerous. It is quite easy for a user to activate or deactive all categories in a single command.
In MySQL you don't have true and false, but only 0 and 1 (INT). So change your queries to something like this:
$sql = "update Categories set IsActive= 0 where CategoryID='$id'"; // FALSE
$sql = "update Categories set IsActive= 1 where CategoryID='$id'"; // TRUE
Additionally I see that in the first piece of code you correctly do this: if row is active print a link to deactivate (if 1 then print 0), and viceversa.
But in the second piece of code you get the value you have to set in the $status variable, and then you say again if 1 then store 0. This is a mistake. In fact, this way you always run an UPDATE query that set the active status to its current value, because of the double swap.
That is, try to swap the queries in the second piece of code, like this:
if ($status == "0")
{
$sql = "update Categories set IsActive=0 where CategoryID='$id'";
$result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error());
}
else if($status == "1")
{
$sql = "update Categories set IsActive=1 where CategoryID='$id'";
$result = mysql_query($sql) or die("Could not insert data into DB: " . mysql_error());
}
Related
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
My Insert query is :
function CreateResult($init_quizz_id,$result_title,$result_image,$result_description) {
$sql = "INSERT INTO result_quizz(init_quizz_id,result_title
,result_image,result_description)
VALUES('$init_quizz_id','$result_title','$result_image','$result_description')";
if ( $GLOBALS['conn']->query($sql) === TRUE) {
echo "Result Added";
$sql2 = "UPDATE 'init_quizz' SET 'results_count' = 'results_count' +1 WHERE 'quizz_id' = '$init_quizz_id'";
$GLOBALS['conn']->query($sql2);
if (!$GLOBALS['conn']->query($sql2)) {
echo ' NO UPDATE';
}
}
}
Lets say i have init_quizz table with the questions, and another table quizz_results. I want to increase the results_count on every quizz when result is added. My result table is hoilding also an init_quizz_id which is the actual ID of the quizz.
Im beginner so im looking for any solution to that.
Thanks
edit: fixed the error on the second query( sql2 ) and getting "not updated" msg. Seems like my second query is completely wrong. Any ideas?
#barmar was right, i found a better solution for my counter instead of UPDATE, i just returning the affected rows which have quizz_id from my results table.
function GetResultsCountByID($quizz_id) {
global $conn;
$sql = "SELECT * FROM result_quizz WHERE init_quizz_id = '$quizz_id'";
$result = $conn->query($sql);
return mysqli_affected_rows($conn);
}
I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.
I have the following PHP script that I am trying to execute. Its very simple yet I am overlooking something since it is not working correctly. If a user toggles a radio button, this script is called and the page is refreshed. However, the "enabled" column in MySQL never updates going from "0" to "1". If I manually enter the value of the enabled column to "1" then the script executes updating the value of the enabled column back to "0" but never to "1" again. What am I overlooking?
$sql="SELECT enabled FROM somecolumn.persist";
$row = mysql_fetch_row($sql);
$enabled=$row[0];
if ($enabled==0) {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '1' WHERE `persist`.`enabled` =0";
} else {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '0' WHERE `persist`.`enabled` =1";
}
mysql_query($query);
It seems like all you are doing is toggling the column value for all records in the given table. Why even bother reading the value from the database and then doing an update? You can simply do an update right off the bat.
$sql = "UPDATE `somecolumn`.`persist` SET `enabled` = ABS(`enabled` - 1)";
$result = mysql_query($sql);
if (false === $result) { // something went wrong
throw new Exception('Query "'. $sql . '" failed with error: ' . mysql_error());
}
This would flip all 1's to 0's and 0's to 1' without having to do any SELECT at all.
According this: http://php.net/manual/bg/function.mysql-fetch-row.php
You should write this code:
$sql="SELECT enabled FROM somecolumn.persist";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$enabled=$row[0];
if ($enabled==0) {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '1' WHERE `persist`.`enabled` =0";
} else {
$query="UPDATE `somecolumn`.`persist` SET `enabled` = '0' WHERE `persist`.`enabled` =1";
}
mysql_query($query);
Note that msql_ functions are deprecated and will be removed in future versions of php. You should consider changing your code to use PDO or MySQLi libraries.
The below script inputs data to a database this takes some information from a form then stores them in to the database. And I'm also using uplodify to upload a image file and store the file name in the database but my issue is this data processing script keeps updating the row ID one never jumps to the second line I tried every thing can some one help me with this or show me what I'm doing wrong.
Also this checks the ID and if it's not equal to 1 then does an insertion if it's equal then update it but this not happening.
The ID is auto incrementing.
My script
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo ORDER BY ID DESC LIMIT 1");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
//$poiId = $_REQUEST['pID'];
if($row['ID'] != "1"){
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
I tried u r suggestions but it's still the same now my code for the update is looks like this.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID`='".$row['ID']."'";
But still it keeps up dating the ID 1 not moving on to the next one.
Your update query is missing a WHERE clause. Try this:
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE ID = '".$row['ID']."'";
Also be beware of MySQL Injections: http://en.wikipedia.org/wiki/SQL_injection
To check why your update failed, you should call mysql_error in your last else clause :
} else {
echo mysql_error();
}
As for the first problem : if you never insert a new record (I don't see how that could happen, provided your code), you will never have a record whose ID is 2.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
You need a where clause in this sql to specify a record to update. Currently it is updating all records.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID` = ".$row['id']";";
You will need to set an $id variable for this to work.