PHP If Statement for MySQL Query - php

For the life of me I cannot figure this one out, still new so I am probably overlooking.
Based on a POST value, I would like to perform 1 of 3 MySQL queries. I have verified that each query works on its own, when I add the if statement nothing updates. Also not receiving any MySQL errors.
If the POST value is "on" or "off" run the corresponding query to update all columns.
If the POST value is anything else (would be a column number), toggle that column.
<!-- language: lang-php -->
mysql_select_db("lightup") or die(mysql_error());
if ($light=="on")
{
$query = mysql_query("UPDATE Homes SET L1Status='0',L2Status='0',L3Status='0',L4Status='0',L5Status='0',L6Status='0',L7Status='0',L8Status='0',L9Status='0',L10Status='0' WHERE HomeID=$id") or die(mysql_error());
}
elseif ($light=="off")
{
$query = mysql_query("UPDATE Homes SET L1Status='0',L2Status='0',L3Status='0',L4Status='0',L5Status='0',L6Status='0',L7Status='0',L8Status='0',L9Status='0',L10Status='0' WHERE HomeID=$id") or die(mysql_error());
}
else()
{
$query = mysql_query("UPDATE Homes SET $lightcolumn = !$lightcolumn WHERE HomeID=$id") or die(mysql_error());
}
mysql_close($link);
Any thoughts?

You have an error in your syntax in your last else, remove the parens, so instead of this:
else()
it should be this
else

Related

PHP - Update each row in MySQL table from a web form

I populate a web form with rows of data. Some of the fields I need to be updatable so I put the value into a text field. MySQL query is:
SELECT * FROM results WHERE EventID = %s AND CompNo = %s", GetSQLValueString($colname_rsResults, "int"),GetSQLValueString($colname2_rsResults, "int"));
EventID and CompNo are passed in the URL.
Let's say the result is 50 rows. I want to be able to update the Name field (eg, make correction to the spelling), click a button and have the code update the database with any new values. It doesn't matter that most of the values will not change as this is a very infrequent operation.
I used to be able to do this in ASP but I can't seem to do in PHP.
This is the code I am using and I think it is completely wrong!!
if ((isset($_POST["JM_update"])) && ($_POST["JM_update"] == "form1")) {
$i = 0;
$j = $totalRows_rsResults;
while($i < $j)
$resultID=$_GET['ResultID'];
$vDelete=$_GET['Del'];
if ($vDelete == 1) {
$delSQL = sprintf("DELETE FROM Results WHERE ResultID=$resultID");
mysql_query($delSQL,$connFeisResults);
} else {
$name=$_GET['Name'];
$qual=$_GET['Qual'];
$updateSQL = sprintf("UPDATE results SET Name = ".$name{$i}.", Qual = ".$qual[$i]." WHERE ResultID=$resultID");
mysql_query($updateSQL, $connFeisResults);
$i++;
}
}
There is also a checkbox at the end of each row to check if I need that record deleted. That doesn't work either!!
I am using Dreamweaver CS6 and trying to adapt the update behaviours etc.
Any thoughts? Many thanks in advance.
It looks like you're missing an opening brace after your while statement.
--UPDATED
Also, check your sprintf statements -- they look wrong, and they look like they're writing the raw '$resultID' to the SQL String, instead of the value within it.
See how to do it here: http://www.talkphp.com/general/1062-securing-your-mysql-queries-sprintf.html

Checking with PHP should table update should be done

Hi to all of you programmers. I want disable table update in my database if inputted value is lower than value in db. The code looks ok, but update always executes. This is my code:
$sql="UPDATE student SET _id_year='$_year' WHERE _index='$_index'";
$check1="SELECT _id_year FROM student WHERE _index='$_index'";
if('$_year'>'$check1')
{
mysqli_query($con,$sql);
}
Note: _id_year and _index are values from DB, and $_year,$_index are inputted values.
$con is connection to database.
First execute your select query and get $check1. Then compare.
$qry = "SELECT _id_year FROM student WHERE _index='$_index'";
$exec = mysqli_query($con,$qry);
$result = mysqli_fetch_object($result);
$check1 = $result->_id_year ;
Also, you Don't have use single quotes. Try this,
if($_year > $check1)
{
mysqli_query($con,$sql);
}
Using SafeMysql the code would be almost the same as you wrote, but it will actually run these queries and also make it safe:
$check=$db->getOne("SELECT _id_year FROM student WHERE _index=?s",$_index);
if($_year > $check )
{
$db->query("UPDATE student SET _id_year=?s WHERE _index=?s",$_year,$_index);
}
You should execute the $check1 query first, get it's result, then compare it with you $_year variable
It is always true because of the quoted field of your PHP it should not be qouted
if($_year>$check1)
{
mysqli_query($con,$sql);
}

my mysql table doesnt get refreshed what to do

after inseet/delete /update i have to manually update the page until i see the result..why? how can i solve this problem
if (isset($_POST['action']) && $_POST['action']=='submitted') {
if (isset($_POST['update'])) {
$selected = $_POST['selected'];
for ($i=0; $i<$columncount;$i++){
$value[$i] = $_POST[$name[$i]];
foreach ($selected as $j)
mysql_query ("UPDATE $tablename set $name[$i]='".$value[$i][$j]." 'WHERE $name[0]=".$value[0][$j]);}
}
its reading table value from a form and updating
Because you update the database after displaying the table.
In other words, you fetch the values, display them, then update them. To fix this just put the above code above the table display.
Other than the obvious SQL injection vulnerabilities that are just begging to get your server pwn3d, you have no error handling whatsoever on your query - you're assuming it succeeded. Why not take the extra 2 seconds to try and handle the possibility that your query might actually have a syntax error?
$result = mysql_query(...) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
Try this one. Hope it will work
mysql_query ("UPDATE ".$tablename." set ".$name[$i]."='".$value[$i][$j]."' WHERE ".$name[0]."='".$value[0][$j]."';");}

UPDATE sql not affecting database

I have this code. Its returning 1 but there is no change on the database!
<?
include ("../connect.php");
$id = $_REQUEST['id'];
$stat = $_REQUEST['changeTo'];
$prod = $_REQUEST['product'];
echo mysql_query("UPDATE $prod SET STATUS = '$stat' WHERE ID = '$id'");
echo mysql_error();
?>
An error will only be returned on an UPDATE statement if a SQL error occurs. If no rows are affected the query is still successful and reported as such.
Make sure all of the variables used in the query contain valid values and that the query should actually affect any records in your database.
My first thought is that $id doesn't exist, can you manually enter an id that you know exists and try running that once? just to rule it out if nothing else
I added this in the hopes that I could get an answer vote :)
Try the SQL-Statement direct with values set by code.

mysql_affected_rows() returns 0 for UPDATE statement even when an update actually happens

I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
Newer versions of MySQL are clever enough to see if modification is done or not. Lets say you fired up an UPDATE Statement:
UPDATE tb_Employee_Stats SET lazy = 1 WHERE ep_id = 1234
Lets say if the Column's Value is already 1; then no update process occurs thus mysql_affected_rows() will return 0; else if Column lazy had some other value rather than 1, then 1 is returned. There is no other possibilities except for human errors.
The following notes will be helpful for you,
mysql_affected_rows() returns
+0: a row wasn't updated or inserted (likely because the row already existed,
but no field values were actually changed during the UPDATE).
+1: a row was inserted
+2: a row was updated
-1: in case of error.
mysqli affected rows developer notes
Have you tried using the MySQL function ROW_COUNT directly?
mysql_query('UPDATE myTable SET foo = 1 WHERE bar = 2');
if(mysql_result(mysql_query('SELECT ROW_COUNT()'), 0, 0)) {
print "updated";
}
else {
print "no updates made";
}
More information on the use of ROW_COUNT and the other MySQL information functions is at: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
mysqli_affected_rows requires you to pass the reference to your database connection as the only parameter, instead of the reference to your mysqli query. eg.
$dbref=mysqli_connect("dbserver","dbusername","dbpassword","dbname");
$updateQuery = mysqli_query($dbref,"UPDATE myTable SET foo=1 WHERE bar=2");
echo mysqli_affected_rows($dbref);
NOT
echo mysqli_affected_rows($updateQuery);
Try connecting like this:
$connection = mysql_connect(...,...,...);
and then call like this
if(mysql_affected_rows($connection) > 0)
echo "affected";
} else { ...
I think you need to try something else in update then foo=1. Put something totaly different then you wil see is it updating or not without if loop. then if it does, your if loop should work.
You work this?
$timestamp=mktime();
$updateQuery = "UPDATE myTable SET foo=1, timestamp={$timestamp} WHERE bar=2";
mysql_query($updateQuery);
$updateQuery = "SELECT COUNT(*) FROM myTable WHERE timestamp={$timestamp}";
$res=mysql_query($updateQuery);
$row=mysql_fetch_row($res);
if ($row[0]>0) {
echo "affected!";
}
else {
echo "not affected";
}
This is because mySql is checking whether the field made any change or not,
To over come this, I created a new TINY field 'DIDUPDATE' in the table.
added this to your query 'DIDUPDATE=DIDUPDATE*-1'
it looks like.
$updateQuery = "UPDATE myTable SET foo=1, DIDUPDATE=DIDUPDATE*-1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0)
{
echo "affected!";
}
else
{
echo "not affected";
}
it works fine!!!
Was My Tought !
I was just about to tell to check if the function's being called many times !
Just a little advice:
try using isset() & POST / GET or something like that;
if ( isset( $_POST['Update'] == 'yes' ) ) :
// your code goes here ...
endif;
Hope it was clear and useful, Ciao :)

Categories