Update command not working for mysql - php

I have been trying to get mysql entries to update via php from ios. I realize that I have made another question about update commands (see MySQL Update command not working) but this is a VERY different script that I am trying (and much simpler). However, I cannot get this to update either! What am I doing wrong? (ps. I have also tried this command with AND's instead of commas inbetween the sets and I have also tried $_POST...and I am connecting to my database). Also, I am just trying to figure out how to get the update command working...then I will learn how to sql inject. I have also tried manual values and still nothing.
<?php
$login = $_GET["log1b"];
$dogname = $_GET["dogname"];
$city = $_GET["city"];
$pass = $_GET["pass"];
$dogusername = $_GET["username"];
$mcode = $_GET["mcode"];
$con = mysql_connect("(censored)");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("(censored)", $con);
mysql_query("UPDATE login SET dogname = '$dogname', city = '$city', pass = '$pass', username = '$dogusername', mcode = '$mcode' WHERE login = '$login'");
mysql_close($con);
?>
or in xcode...
NSString *urlString = [NSString stringWithFormat:#"http://(censored)?username=%#&dogname=%#&mcode=%#&pass=%#&city%#&log1b=%#", fldUsername.text, flddogname.text, fldmcode.text, fldpass.text, fldcity.text, log1b];

I think you are missing a ' around $city.
Also you may want to use mysql_real_escape_string.
The syntax looks good to me now. You should try to it manually (using something like MySQL Toad) to make sure the query is valid.

Related

UPDATE to current date (PHP)

im trying to update date on the table. YYYY-MM-DD HH-MM-SS.
There is the code i have.
It takes information from table and after that I want it to set date in that table to current time
<?php
$username = "root";
$password = "sawasq";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$code = $_POST['kodas'];
$code = stripslashes($code);
$sql = mysql_query("SELECT * FROM dviraciai WHERE ID='$code'");
$Pavadinimas = 'Pavadinimas';
$Metai = 'Metai';
$Status = 'Status';
$rows = mysql_fetch_assoc($sql);
echo 'Pavadinimas: ' . $rows[$Pavadinimas] . '<br>';
echo 'Metai: ' . $rows[$Metai] . '<br>';
echo 'Status: ' . $rows[$Status] . '<br>';
$sql2 = mysql_query("UPDATE Dviraciai WHERE ID='$code' SET date=CONCAT(CURDATE(),' ',time(mytime))");
mysql_close();
?>
I get $code from input.
Dviraciai is my table.
I dont get any error. But when i enter my $code it shows the info but doesnt change time in table after I restart phpMyAdmin
Your query is totally wrong, and since you never bother checking for errors and simply ASSUME nothing could ever go wrong...
Update syntax is
UPDATE ... SET ... WHERE...
You have the set/where reversed. And note that restarting phpmyadmin is beyond pointless. It's a MANAGEMENT INTERFACE. It's not the database itself. It's like trying to change the outcome of a tv show by turning your tv on/off.... the show's going to end up broadcasting the same ending no matter what you to do with your TV.
Never assume success with DB operations. Even if your SQL is 100% syntactically perfect (and yours definitely isn't), there's far too many OTHER reasons for a query to fail. Assuming success is, frankly, just plain stupid. Always assume failure, check for failure, and treat success as a pleasant surprise. At bare minimum, have something like this:
$result = mysql_query(...) or die(mysql_error());

SQL Update code issue/PHP injection

I am having an issue with my SQL Update script.
It prints "Motto Changed" but doesn't update the row. My code is all correct according to many tutorials. Please Help
$sql="UPDATE loadout SET motto='".$_POST['motto']."' WHERE steamid='".$steamid."'";
UPDATE AGAIN:
<?php
require "../requires/php/steam.php";
$dbhost = '**';
$dbname = 'battlefield';
$dbuser = 'battlefield';
$dbpass = '**';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$authserver = bcsub( SteamID(), '76561197960265728' ) & 1;
$authid = ( bcsub( SteamID(), '76561197960265728' ) - $authserver ) / 2;
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
mysql_select_db($dbname, $con);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "Motto Changed";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo"Motto changed on {$n} row(s)";
mysql_close($con)
?>
Never interpolate $_POST variables directly into SQL strings. You can't trust $_POST variables, they may easily contain characters that modify your SQL syntax, and that's what causes SQL injection vulnerabilties.
The weird thing is that you create an escaped version as $motto and then you never use it (as per comment from #Arth).
Always escape strings that you interpolate into SQL, even if you think they are "safe." For example, your $steamid contains only literal text that you control, plus a couple of integers. That should be safe, but what if some other developer changes the format of a steamid next year? If you escape it, you can't go wrong.
$steamid = mysql_real_escape_string("STEAM_0:$authserver:$authid");
$motto = mysql_real_escape_string($_POST['motto']);
$sql="UPDATE loadout SET motto='{$motto}' WHERE steamid='{$steamid}'";
Of course, the best practice is to use query parameters. You are using PHP's deprecated mysql extension, which doesn't support query parameters. But I understand if you're not ready to rewrite a lot of code to switch to PDO. When you are, follow examples in How can I prevent SQL-injection in PHP?
Another issue: if you want to know if the UPDATE affected rows, don't assume it did just because the UPDATE didn't return an error. It's not an error if your condition in your WHERE clause simply matched zero rows. It's also not an error if the UPDATE matched a row, but the motto already contained the string you tried to set.
After the UPDATE, check the number of affected rows:
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
$n = mysql_affected_rows();
echo "Motto changed on {$n} row(s)";

Inserting data into two separate tables using PHP

I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ($desc_query) it won't update any table.
Here is my code:
$name= strip_tags($_POST['name']);
$l_name= strip_tags($_POST['last_name']);
$c_id = strip_tags($_POST['company_id']);
$a_d = strip_tags($_POST['add_description']);
$d_t = strip_tags($_POST['desc_text']);
$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!");
mysql_select_db('database_db') or die('could not connect to database!');
//inserting names
$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");
//inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
$desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}
You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks).
I would recommend sanitizing all user provided data like so:
$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);
Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL.
Have you tried to echo out the queries and then to run them directly on the database?
Without any more information about the database we can't really tell if the queries themselves are valid.

Transferred to new hosting/server - Now having issues with using MySQL for form validation

I'm having a lot of problems with the new hosting, but the more I look at it, it seems that they're all related to doing checks in my database when validating logins, registrations, and submissions. Here's an example of one.
I use jQuery to validate forms. One I use to determine if a username actually exists when a user is trying to log in (don't worry, I also check server side). On my development server, this works flawlessly. If you're not familiar with jQuery Validation, basically this returns a true or false back to the server in a form of some kind of JSON, but I'm not entirely knowledgeable on that part.
The code:
//Database Information vars (removed)
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT username FROM registerusers WHERE username='$username';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
The problem with this is that it always refers to the first clause and returns true, even if the username does not exist. For whatever reason, I think it's always returning 1 for mysql_num_rows($res).
This EXACT code (except for new database vars which I've checked a hundred times to be accurate) works as intended on my development server still. I can only assume that it has something to do with the new server, and that's why I'm asking Stack Overflow, because I have no clue.
The problem is that register_globals is enabled.
This poses a high security problem which is why it is disabled and deprecated.
Changing $login_username to $_GET['login_username']solves the problem.
Using the $_GET and $_POST super global arrays is not a security problem, but you should always sanitize your input (like you do with mysql_real_escape_string()).
Have you tried setting the MySQL connection to a variable, then calling the connection variable as the second parameter inside of the mysql_query? This has sometimes given me an issue on some servers, especially if they have certain debugging methods, errors, and warnings shut off by default:
//Database Information vars (removed)
$connect = mysql_connect ($dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT `username` FROM `registerusers` WHERE `username` = '".$username."';";
$res = mysql_query($query, $connect);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
I've also changed the $query to a concatenated string with the variable, as some servers I have worked on sometimes are finicky in terms of putting variables inside of a string without delimiting them with "..".

my insert query is working in my localhost but not in web server

I am using flex builder 3 to insert into mysql database using php and everything is working perfectly in my localhost, the problem is when I deploy the project in the web server and run it, it connect to the database but i can't insert data ( it shows nothing when i insert data )
another stupid thing is in another piece of code for retrieving (select) data that works good on both my localhost and web server.
here is the php code:
<?php
$host = "******";
$user = "******";
$pass = "******";
$database = "******";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$nickname = $_POST['nickname'];
$steam = $_POST['steam'];
$c1 = $_POST['c1'];
$c2 = $_POST['c2'];
$c3 = $_POST['c3'];
$results = mysql_query("INSERT INTO `phantom`.`members` (`TF2_Nickname` ,`Steam_User_Name`,
`class1` ,`class2` ,`class3` ,`time`) VALUES ($nickname, $steam, $c1, $c2, $c3,NOW())");
?>
You need to declare the values as strings in your MySQL query as well:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('$nickname', '$steam', '$c1', '$c2', '$c3', NOW())"
And you should also prepare them in some way to avoid that they are mistakenly treated as SQL command (see SQL Injection). PHP has the mysql_real_escape_string function to do that:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('".mysql_real_escape_string($nickname)."', '".mysql_real_escape_string($steam)."', '".mysql_real_escape_string($c1)."', '".mysql_real_escape_string($c2)."', '".mysql_real_escape_string($c3)."', NOW())"
Insert into requires either user right or admin right. Check if by chance You didnt modify somewhere in the code these rights, e.g., You changed by hand the name of your admin... If it works the select it is because selecting doesnt need so many rights. Even non user status can retrieve info through select but insert needs special rights. You know your code so think about this difference

Categories