Updating SQL rows where row matches user log in ID - php

I have a problem with this line of code - I have spent most of the day trying to get this resolved - can any one help?
Here is the code that is causing the problem form what I can see! The problem is around the $qry...
$qry = "INSERT INTO members (employer, flat) VALUES('$employ','$address') WHERE login='$_login'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: member-profile.php");
exit();
}else {
die("Query failed");
}
?>
ERROR showing is:
( ! ) Notice: Undefined variable: _login in C:\wamp\www\123456\update.php on line 67
Thanks all.

First variable $_login is Undefined, and second, it seems you are trying to update.
You do not user WHERE for SELECT query.
If you want to update, it then your query should very much like this:
$sql = 'UPDATE table SET username = '$username' WHERE id = $_login;
variable $_login means, pretty much, the variable $_login is not defined. You must give it a value, before you can you expect it to work in your query.

INSERT doesn't allow the WHERE attribute, you need to use UPDATE instead
"UPDATE members SET employer='$employ', flat='$address' WHERE login='$_login'"
Be sure to prevent SQL injections and since mysql_* functions are deprecated you should switch to MySQLi or PDO
As for the error itself, you need to check if the variables are defined that you are using
if (!isSet($_login))
// do sth

Related

Check if value is found in SQL table within PHP script?

I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }

How avoid duplicate data entry via php to mysql?

We have a table vehicle and a simple php form. Before inserting data I do check if the vehicle registration number exist but some client pc could enter duplicate entries. Below is the code snippet. What else could be causing this ?
$vehicleRegistrationNumber=$_POST['vehicleRegistrationNumber'];
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."'";
$result1 = mysqli_query($link,$selectQuery1);
$row1 = mysqli_fetch_array($result1, MYSQL_ASSOC);
$n1 = mysqli_num_rows($result1);
if($n1 > 0) {
$status="<span class=\"statusFailed\">: Vehicle ".$vehicleRegistrationNumber." Already Exist.</span>";
}
else {
//insert codes
}
First of all your code is vulnerable to SQL injection. This check can be bypassed by submitting something like XYZ0001' AND 1='0 or even more malicious values. To prevent this, use prepared statements and param binding instead of string concatenation.
Other possibility is simply user mistake, for example trailing space ("XYZ001" != "XYZ0001 ") that is hard to spot on the first glance ad records in DB. Before checking its existence in DB you should check with PHP if submitted value includes only allowed chars and is free from common mistakes.
try this with group by
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."' GROUP BY vehicleRegistrationNumber";
The best way is to handle it on the SQL side. Just define the field as UNIQUE INDEX.
Now when trying to insert a duplicate index an error will be thrown and you can catch it like this:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
Like this you can avoid the select query before every insert query. Just handle the error as you want.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

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 - strange thing with update and select statements

I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.

Categories