I'm learning PHP and getting a little frustrated. I have an html form that is sending data to another php page $_POST["id"];.
On a 2nd php page I'm trying have the "available" column in the table either switch to 1 or 0. If it's already 1 go to 0, and if it's 0 go to 1.
I know my code is probably completely wrong and messy but please excuse me as I'm still learning.
if ($row["available"] == 1) {
//$row["available"] = 0;
$sql = "UPDATE check_in_out SET available=0 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
} else {
//$row["available"] = 1;
$sql = "UPDATE check_in_out SET available=1 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
If you want to toggle the value you can use this:
$sql = "UPDATE check_in_out SET available = (1-available) WHERE id='".$_POST["id"]."'";
or
$sql = "UPDATE check_in_out SET available = IF(available = 0, 1, 0) WHERE id='".$_POST["id"]."'";
Related
im new student of php and mysql. I'm doing a voluntary little game for class. But I can not understand why when doing mysqli query it returns an int 0 when the database has 500 assigned. The game consists of a user who bets a certain amount of coins of his account, then a dice decides whether you win or not, taking 1,2,3 you lose, 4,5,6 you win. I post here the error or whatever this is.
include('conexion.php');
include('session.php');
$usuario=$_SESSION["username"];
$apuesta =$_POST["apuesta"];
$coins= "SELECT coins FROM `users` WHERE `usuario` = \"$usuario\"";
if (mysqli_query($conn, $coins)){
echo "<br>";
echo "hola";
echo "<br>";
var_dump($coins);
echo "<br>";
$coins2 = (int)$coins;
var_dump($coins2);
echo "<br>";
echo "<br>";
var_dump($coins2);
echo "<br>";
if ($apuesta>=$coins2) {
echo "No tienes suficiente saldo";
echo "<br>";
}else {
$dado = rand(1,6);
if ($dado >3) {
$apuesta = $coins2 + $apuesta;
$cambiocartera = "UPDATE `users` SET `coins` = $apuesta WHERE `users`.`usuario` = '$usuario'";
echo "<br>";
echo "<h1>Ganaste = $dado";
header( "refresh:3;url=dashboard.php");
}
elseif ($dado<4) {
$apuesta = $coins2-$apuesta;
$cambiocartera = "UPDATE `users` SET `coins` = $apuesta WHERE `users`.`usuario` = '$usuario'";
echo "<br>";
echo "<h1>Perdiste = $dado</h1>";
header( "refresh:3;url=dashboard.php" );
}
}
}else {
echo"error";
}
My browser message about the int on 0 that i dont understand why.
$coins is the string containing the query, it's not the column you're retrieving from the table. When you convert a string to a number, it returns 0 if there's nothing numeric at the beginning.
You need to assign the result of mysqli_query() to a variable, then call a fetch function on that.
if ($result = mysqli_query($conn, $coins)) {
$row = mysqli_fetch_assoc($result);
$num_coins = $row['coins'];
var_dump($num_coins);
I am trying to update my SQL table with the help of this php code:
$description = "Something about myself";
$insert = $con->prepare("INSERT INTO kys_write (Author, writing , Title , Description , Assets) VALUES (?,?,?,?,?)");
$insert->bind_param("ssssi",$author,$data,$title,$description, $ImageExist);
$insert->execute();
$statement = $con->prepare("SELECT id FROM kys_write WHERE Title=?");
$statement->bind_param("s",$title);
$statement->execute();
$statement->bind_result($lastId);
//Everything works fine if this whole part is removed
$sql = "UPDATE kys_essentials SET LastId=".$lastId;
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
I am getting a error:
Error updating records:Commands out of sync, you cannot run this command now.
What causes this, and how can I avoid it?
It clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
You can simplify you code using one query . no use of extra select query
$sql = "UPDATE kys_essentials SET LastId = (SELECT id FROM kys_write WHERE Title='$Title')";
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
Fetch your $lastId after the binding and put ' ' for value/s, like this:
//your codes
$statement->bind_result($lastId);
while ($statement->fetch()){
$sql = "UPDATE kys_essentials SET LastId='".$lastId."'";
if ($con->query($sql) === TRUE){
echo "Record updated successfully";
} else{
echo "Error updating record: " . $con->error;
}
}
table name -- breaking_news
field name -- status
I have created a single page and passes id from link click.
Now I check if status not empty and status equal to Inactive
then update status = Active Else update status Inactive
but it is not working properly.
It Only Works For If Condition.
The ELSE Condition of Code is Not Working . plz suggest me how to write in if else properly...
<td><img src="img/active.png" width="24" height="24" border="0" title="Active" /></td>
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!empty($row) && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>
Try this code
">
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!$row && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>
you have just to ask if $row was have more or not, be cause mysql_fetch_assocreturn false if it's empty look to this manual : mysql_fetch_assoc PHP
you have just do not use empty()
Or like that :
if($row = mysql_fetch_assoc($result))
{
if($row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
If you have not found a row, there is nothing to update...
You may wish to do something like this:
<?php
if (!empty($row)) {
if ($row['status'] == 'Inactive') {
//update to active
}
else if ($row['status'] == 'Active') {
//update to inactive
}
}
also you've got a typo in the second call to $_GET array: $_GET['status_inactive']. You should be updating the same row but with different status value.
EDIT
#toto21 I don't have enough reputation to comment on your answers but no, your answer is wrong. As I mentioned at the top - if there is no row fetched then there is nothing in the db for you to update, so your else statement makes no sense.
Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!
<?php
if (intval($_GET['page']) == 0) {
redirect_to("staff.php");
}
$id = mysqli_prep($_GET['page']);
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
$result = mysqli_query($connection, $query3);
if (mysqli_affected_rows($connection) == 1) {
redirect_to("staff.php");
} else {
// Deletion Failed
echo $id ."<br />" . $query3 . "<br />" . $result . "<p>Subject
deletion failed.</p>";
echo "<p>" . mysqli_error() . "</p>";
echo "Return to Main Page";
}
// Keep on working Edit:2#
mysqli_query($connection, "DELETE FROM pages WHERE id = 11 ");
//- Works
Edit 3#
$id = $_GET['page'];
echo "<p>" . $id ."</p>";
$query3 ="DELETE FROM pages WHERE id = {$id} ";
mysqli_query($connection,$query3 );
// Still Works -- YaY for working backwards
// Edit #4 By "now it might be obvious what my error was "pages" not "page"
// Thanks everyone - And thank you for telling me about the error page
// My defense - newbie- Anyway Lesson from this - working backwards
// Takes a while, Error checking Fast!!!!!!
?>
$connection is started and selected. The $id is selected successfully, and the $page = $id, but it still will not work. $query 3 seems fine, but Deletion failed. I don't have any idea what the error is. Thanks for any help in advance.
-Josh Edit Check Error Check
You have a comma after the ID:
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
^ remove this
I don't have any idea what the error is.
That's because you didn't check. Every time you prepare or execute a query, you need to check for errors. Most of the functions in mysqli return FALSE if they encounter an error.
$result = mysqli_query($connection, $query3);
if ($result === false) {
trigger_error(mysqli_error($connection), E_USER_ERROR);
header("Location: /error.php");
exit;
}
The failure to check for error cases is one of the most common blunders committed by database programmers.
if ($page == get_page_by_id($id)) {
== for comparison
=== to compare the value and the cast
$val = true;
if ($val === true) {
echo "\$val is bool(true)";
}
if ($val == "true") {
echo "\$val matches value";
}
if ($val === "true") {
// this will never happen
} else {
echo "\$val doesnt === \"true\"";
}
try to use php_flag display_errors on in your .htaccess
this will allow you to see and identify php errors.