The script I'm using is
if($profile['username'] == $user['username']) {
$db->query("UPDATE users SET newcomments = 0 WHERE username = '$user[username]'");
echo "This is a test";
}
(Note that $db->query is exactly the same as mysql_query)
For some very odd reason, the MySQL query is being performed even if the defined condition is false
The "This is a test" works properly and only appears when the condition is met, but the MySQL query is performed anyway
Whats the problem with it?
Typically the answer to such questions is somewhere else. Maybe similar SQL code is called elsewhere?
Your code looks fine.
Try:
echo "<pre>";
print_r($profile);
print_r($user);
and see if it is what you expected.
I'm having trouble believing this, either way try something like this.
$query="";
if($profile['username'] == $user['username']) {
$query ="UPDATE users SET newcomments = 0 WHERE username = '" . $user[username] . "' ";
echo "This is a test";
}
echo $query;
$db->query($query);
Related
My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
I got a little problem here with my SQL query...
I debugged where the problem resides and realized that the varchar/text column seemed to stop my php function.
Here is my code:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
if($dataTest['dos_id'] == $myparameter) {
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" selected>'.$dataTest['dos_nom'].'</option>';
}
}
The problem is in the value $dataTest['dos_nom']. Without which my query works (it prints the page normally), but I don't know why. With it, it doesn't work (it prints the top of the page, and nothing from/after my php function)...
To be precise, i use it in an ajax function.
Thanks in advance!
EDIT: I tried to print only 1 row from 'dos-nom', it works! But i when try to print out more than 1 row, the function stops!
My code:
$queryTest2 = mysqli_query($link, "SELECT * FROM dossier");
while($dataTest2 = mysqli_fetch_assoc($queryTest2))
{
$test[0] = $dataTest2['dos_nom'];
}
if($dataTest['dos_id'] == $dos_id)
{
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" >'.$test[0].'</option>';
}
It prints only the last line this way. If i put a WHERE in the query it will stop the function, so i don't know what to do!
ANSWER:
É / À were in my database, i replaced them by E and A, problem solved!
try to use addslashes() function like
addslashes($dataTest['dos_nom'])
maybe the value contains some backslash or some junk characters which may be breaking your code
I see nothing wrong with your code, except the logic - you only output when option is selected.
So as you said (it prints nothing)
Let's try print something:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
$selected = ($dataTest['dos_id'] == $myparameter)?' selected ':' ';
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" '.$selected.'>'.$dataTest['dos_nom'].'</option>';
}
I've been trying to make this code work for hours now but I can't seem to find solution. I've serached all relevant topics and tried to change the code, punctuation etc. but none of them worked for me.
The result is always "Success!" but the database update never works (checked in phpmyadmin).
I hope that you can find the error. The code is the following:
if(empty($_POST['nev']) || empty($_POST['orszag']) || empty($_POST['telefonszam']) || empty($_POST['iranyitoszam'])
|| empty($_POST['megye']) || empty($_POST['varos']) || empty($_POST['utca'])) {
echo "Failure! Missing data...";
}
else {
$nev = mysql_real_escape_string($_POST['nev']);
$orszag = mysql_real_escape_string($_POST['orszag']);
$telefonszamm = mysql_real_escape_string($_POST['telefonszam']);
$iranyitoszam = mysql_real_escape_string($_POST['iranyitoszam']);
$megye = mysql_real_escape_string($_POST['megye']);
$varos = mysql_real_escape_string($_POST['varos']);
$utca = mysql_real_escape_string($_POST['utca']);
$shipping_query = mysql_query("UPDATE users
SET Name=".$nev.", Phone=".$telefonszam.",
Country=".$orszag.", State=".$megye.",
City=".$varos.", ZIP=".$iranyitoszam.",
Road=".$utca."
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
echo "Success!";
}
Thank you for your help!
You're missing quotes around the strings in your query.
$shipping_query = mysql_query("UPDATE users
SET Name='".$nev."', Phone='".$telefonszam."',
Country='".$orszag."', State='".$megye."',
City='".$varos."', ZIP='".$iranyitoszam."',
Road='".$utca."'
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
You also no error checking on your query. So whether it succeeds or fails it will always say, "success". You need to check to see if there is a MySQL error ir rows updated before you can declare success.
Name, Phone, Country etc etc seam like VARCHARs. so, it should be treated as a string.
So, query should be like.
"UPDATE users SET Name='".$nev."', Phone='".$telefonszam."',Country='".$orszag."', State='".$megye."',City='".$varos."', ZIP='".$iranyitoszam."',Road='".$utca."' WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'"
As other answers have pointed out, you're missing quotes around your string variables.
When you're MySQL queries are failing to execute, try echoing your queries while debugging to see what exactly you're sending to the database.
$myValue = "Green";
$mySQL = "UPDATE MyTable SET MyColor = " . $myValue;
$myQuery = mysql_query($mySQL);
echo $mySQL;
Spotting the error visually is much easier when the entire SQL string is assembled in one piece.
You can also copy the assembled SQL string and paste it straight into a phpmyadmin query to get debugging information from it.
I have this sql statement that returns rows from a customer table. The user has the option for searching with what ever they want to type in. I had this working, until I tried to protect against sql injecting by using bindValue. Now I can't get any results to return unless the user leaves the textbox blank. Below is my code.
Model
function searchMyCusts($field, $query){
$data = null;
$msg = null;
$status = null;
$sth = $this->db->prepare("SELECT ".CustomerFields::ID.",".CustomerFields::FirstName.",".CustomerFields::LastName.",".CustomerFields::PhoneNumber." FROM ".CustomerFields::TableName." WHERE '$field' LIKE :query");
$sth->bindValue(':query', $query);
if ($sth->execute()){
$status = "success";
$msg = "Customer entry successfully altered";
$data = $this->smartFetchAll($sth);
}else{
$status = "error";
$msg = "An error occurred. :".$sth->errorInfo()[2];
}
$jsonData = json_encode($this->buildResponseArray($status, $msg, $data));
return $jsonData;
}
In the prepare line at the end I have the values being passed in. Like I said this was working until I attempted to bindValue the query variable.
I would appreciate any insight you may have. Thanks in advance!
Regards
I don't know how could it work before but first of all you need to change
" WHERE '$field' LIKE :query"
to
" WHERE $field LIKE :query"
or
" WHERE `$field` LIKE :query"
You can't use quotes around a column name because it becomes just a literal string which you compare with :query pattern. The query will work but you'll have no rows returned. Either nothing or back ticks.
Secondly $query should contain all necessary wildcard symbols prior to prepare. E.g.
$query = "%new%";
It's not clear whether it's the case from your code
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 :)