Whats wrong with this MySQL Update Query? - mysql

1st I'll give you the query, and then I'll tell you what I am trying to achieve, as I could be soo wrong or soo close.
mysql_query("UPDATE link_building SET
ID=$ID,Site=$Site,Date=$Date,Target_Site=$Target_Site,
Target_Contact_Email=$Target_Contact_Email,
Target_Contact_Name=$Target_Contact_Name,
Link_Type=$Link_Type,Link_Acquired=$Link_Acquired,
Notes=$Notes,Link_URL=$Link_URL WHERE ID=" . $ID);
What am I trying to achieve?
I want to update the fields
("ID","Site","Date","Target_Site","Target_Contact_Email","Target_Contact_Name",
"Link_Type","Link_Acquired","Notes","Link_URL")
in the table link_building with the values stored in the variables
("$ID","$Site","$Date","$Target_Site","$Target_Contact_Email","$Target_Contact_Name",
"$Link_Type","$Link_Acquired","$Notes","$Link_URL")
But I only want to update the record whos Id is equal to $ID.
UPDATE: I DO NOT SEE ANY ERROR. ITS REDIRECTS TO link_building.php and displays success message but doesn't change the data in the MySQL table.

Try escaping the data and removing the update of the ID since its already in your conditions:
mysql_query("UPDATE link_building SET Site='".mysql_real_escape_string($Site)."',Date='".mysql_real_escape_string($Date)."',Target_Site='".mysql_real_escape_string($Target_Site)."', Target_Contact_Email='".mysql_real_escape_string($Target_Contact_Email)."', Target_Contact_Name='".mysql_real_escape_string($Target_Contact_Name)."', Link_Type='".mysql_real_escape_string($Link_Type)."',Link_Acquired='".mysql_real_escape_string($Link_Acquired)."', Notes='".mysql_real_escape_string($Notes)."',Link_URL='".mysql_real_escape_string($Link_URL)."' WHERE ID=" . intval($ID));

For one, you're forgetting that you still need to quote your strings;
mysql_query("UPDATE link_building SET Site='$Site', Date='$Date',".
"Target_Site='$Target_Site', Target_Contact_Email='$Target_Contact_Email',".
"Target_Contact_Name='$Target_Contact_Name', Link_Type='$Link_Type',".
"Link_Acquired='$Link_Acquired', Notes='$Notes', Link_URL='$Link_URL' ".
"WHERE ID=$ID");
Note the added 's around all strings.
Bonus remark; you should really be using mysql_real_escape_string() on your strings before passing them on to the database.

if your columns are named like Target Site (with a space in it), you should adress it like that in your query (wich will force you to add backticks to it). also, you'll have to add quotes to colums that store anything else that strings. your query should look like:
UPDATE
link_building
SET
ID = $ID,
Site = '$Site', // single quotes for values
Date = '$Date', // ...
´Target Site´ = '$Target_Site' // and ´ for fields
[...]
this should solve why the query doesn't work (in addition: not how a bit or formatting makes it much more readable).
you havn't given information about that, but please note that you should always sanitize your variables before using it (your code doesn't look like you do) to avoid sql-injections. you can do this using mysql_real_escape_string or, even better, start using prepared statements.

Related

PHP Registration to MYSQL Database

I have a problem here..
Im currently building a website(blog) where I want people to be able to register. And I want that information to be sent to my MYSQL
This is some of the code:
<?php
$query="INSERT INTO Medlemmar(namn, epost)
VALUES("$_GET[namn]", "$_GET[epost]")";
if (!mysqli_query($mysql_pekare,$query))
{
die("Error: " . mysqli_error($mysql_pekare));
}
echo "Du har lagt till kunden I databasen";
?>
But for some reason i get error on the "VALUES" part.. That im missing a syntax.. WTF am i missing?! Been stuck with this for 1+ hours.. Just had to turn here, usually a quick response! Thanks!
edit: "Parse error: syntax error, unexpected T_VARIABLE"
There are syntax errors all over the place... This needs some work.
<?php
$query = "INSERT INTO Medlemmar(name, epost) VALUES(\"".$_GET['namn']."\", \"".$_GET['epost']."\")";
That should fix the query... You need to learn how to escape \" double quotes so they can be used in the actual query.
try
VALUES ('".$_GET[a]."', '".$_GET[b]."')
or ' and " exchanged.
You are forgetting the single quotation marks around each value
The way you're managing registration is extremely insecure. If you were to set the namn and epost value to a sql query (like SELECT FIRST (username) FROM user_table) then it would execute that as behalf of the original sql query.
if you set username to SELECT FIRST (username) FROM user_table then it would return the first username in the user_table
To avoid this from happening you can use prepared statements which means that you specifically assign a sql query with a placeholder value and then you apply a value to the placeholder.
This would mean that you force the sql query to only execute what you've told it to do.
E.g. You want to JUST INSERT into a table and only do that and nothing else, no SELECT and no table DROP well in that case you create the prepared INSERT query with a placeholder value like this.
$db = new PDO('mysql:host=localhost;dbname=database_name', 'database_user', 'database_user_password');
// Create the register statement for inserting.
// Question mark represent a placeholder for a value
$register = $db->prepare('INSERT INTO users_table (username, password) values (?, ?)');
// Execute the register statement and give it values
// The values need to be parsed over in a array
$register->execute(array("test_user", "test_password"));
I'm not the best at explaining but if you want to understand what EXACTLY is going on here then this is a pretty good article which explains it in more detail.

mysql query text replace issue

I have a joomla database with 'jos_content' table containing the details about the articles.
In that table, the column 'attribs' is of TEXT datatype, which contains data about the article properties, like:
show_pdf_icon=0
show_print_icon=0
show_email_icon=0
I am trying to modify the property 'show_print_icon' so that it will have 1, like this:
show_pdf_icon=0
show_print_icon=1
show_email_icon=0
For this, i have written a query that replaces the 'show_print_icon=0' to 'show_print_icon=1' in the column.
UPDATE jos_content set attribs=replace("attribs", "%print_icon=0\nshow_email%",
"%print_icon=1\nshow_email%") where attribs like '%print_icon=0\nshow_email%';
For some reason, after executing this query, i got the column values as empty.
I could not understand where did i go wrong. What could be the problem with query?
One way is :
$sql = "Select attribs from jos_content";
$db = JFactory::getDBO():
$db->setQuery($sql):
$contents = $db->loadObjectList();
foreach($contents as $content){
$attribs = $content->attribs;
$attribs = explode("\n", $attribs);
if(!$attribs['show_print_icon']){
$attribs['show_print_icon'] = 1;
$content->attribs = implode("\n", $attribs);
// run the update query here for each content
}
}
I'll let you know other way, using Com Content Model
Check the newline character. It may not be \n, it could be also \r\n or just \r, so you can't reliably match on this rule.
Also, why do you need the text surroundig? It just makes your login more complex than it has to be. You will have to be sure to keep consistent data and not have the variables there in another order for example.
I don't know what is your database structure there, but try to match on exactly what you need to change. If it's not possible now, than try to change your logic so you make it possible

MySQL Security Check

Evening all,
Before i make my site live i obviously want to ensure it's secure (or as secure as possible).
I have a search form, an opportunity for a user to upload an entry to a database, and that's about it i think.
So i just want to check what i should be doing to protect things. Firstly, my database is accessed by a dedicated user account (not admin or root), so i think i've got that part locked down.
Secondly, on all my search queries i have this sort of format:
$result = mysql_query(
"SELECT *
FROM table
WHERE fieldname = '" . mysql_real_escape_string($country) . "'
AND county = '" . mysql_real_escape_string($county) . "'
ORDER BY unique_id DESC");
Finally, on the $_POST fields from my submission form, i treat the variables with this BEFORE they are inserted into the database:
$variable = mysql_real_escape_string($variable);
$result = mysql_query(
"INSERT INTO table (columnone)
VALUES ($variable)";
Could anyone let me know what else i should be considering or whether this is acceptable enough?
Thanks in advance, as always,
Dan
The code looks fine, though you should look into using PDO prepared statements if at all possible.
Beyond that, make sure that whatever account your PHP code is using to connect to MySQL has the absolute minimum in the way of permissions. Most web-facing scripts do NOT need alter/drop/create type privileges. Most can get away with only update/insert/select/delete, and maybe even less. This way, even if something goes horribly wrong with your code-level security, a malicious user can't send you a '; drop table students -- type query (re: bobby-tables.com)
Everything you show looks fine in terms of protection against SQL injection, except for
$variable = mysql_real_escape_string($variable);
$result = mysql_query(
"INSERT INTO table (columnone)
VALUES ($variable)";
this desperately needs quotes around $variable - or as #Dan points out, a check for whether it's a number - to be secure. mysql_real_escape_string sanitizes string data only - that means, any attempt to break out of a string delimited by single or double quotes. It provides no protection if the inserted value is not surrounded by quotes.
Have you considered using like MYSQL PDO and bound parameters in your SQL?
http://php.net/manual/en/pdostatement.bindparam.php
My understanding is that this is considerably more secure that using mysql_real_escape_string.

an issue with MySQL query

There is a weird code here that I need to make work.. can you please help me correct it .
mysql_query("insert into table(column) values('$var[0]'));
It looks like you are missing the double quote " at the end of your SQL string.
While you're at it, you should rewrite your query like so:
mysql_query("INSERT INTO table (column) VALUES ('" . mysql_real_escape_string($var[0]) . "')");
...unless you've already escaped $var[0], you should pass all variables through mysql_real_escape_string before interpolating them into an SQL query, to prevent SQL injection attacks.
Do you really have a table that only needs a single column to be populated?
Can you issue the query through your database admin tool directly, rather than going through PHP? What error do you get?
There are many reasons why your code as it currently stands might be falling over - constraints and permissions being just two. If you can post a helpful error message, we can post some helpful advice...
Martin
change the way you are using the variable like so:
<?php
mysql_query("insert into table(column) values('".$var[0]."')");
?>
and close the double quotes at the end as you had forgotten to do so.

Why does my INSERT sometimes fail with "no such field"?

I've been using the following snippet in developements for years. Now all of a sudden I get a DB Error: no such field warning
$process = "process";
$create = $connection->query
(
"INSERT INTO summery (process) VALUES($process)"
);
if (DB::isError($create)) die($create->getMessage($create));
but it's fine if I use numerics
$process = "12345";
$create = $connection->query
(
"INSERT INTO summery (process) VALUES($process)"
);
if (DB::isError($create)) die($create->getMessage($create));
or write the value directly into the expression
$create = $connection->query
(
"INSERT INTO summery (process) VALUES('process')"
);
if (DB::isError($create)) die($create->getMessage($create));
I'm really confused ... any suggestions?
It's always better to use prepared queries and parameter placeholders. Like this in Perl DBI:
my $process=1234;
my $ins_process = $dbh->prepare("INSERT INTO summary (process) values(?)");
$ins_process->execute($process);
For best performance, prepare all your often-used queries right after opening the database connection. Many database engines will store them on the server during the session, much like small temporary stored procedures.
Its also very good for security. Writing the value into an insert string yourself means that you must write the correct escape code at each SQL statement. Using a prepare and execute style means that only one place (execute) needs to know about escaping, if escaping is even necessary.
Ditto what Zan Lynx said about placeholders. But you may still be wondering why your code failed.
It appears that you forgot a crucial detail from the previous code that worked for you for years: quotes.
This (tested) code works fine:
my $thing = 'abcde';
my $sth = $dbh->prepare("INSERT INTO table1 (id,field1)
VALUES (3,'$thing')");
$sth->execute;
But this next code (lacking the quotation marks in the VALUES field just as your first example does) produces the error you report because VALUES (3,$thing) resolves to VALUES (3,abcde) causing your SQL server to look for a field called abcde and there is no field by that name.
my $thing = 'abcde';
my $sth = $dbh->prepare("INSERT INTO table1 (id,field1)
VALUES (3,$thing)");
$sth->execute;
All of this assumes that your first example is not a direct quote of code that failed as you describe and therefore not what you intended. It resolves to:
"INSERT INTO summery (process) VALUES(process)"
which, as mentioned above causes your SQL server to read the item in the VALUES set as another field name. As given, this actually runs on MySQL without complaint and will fill the field called 'process' with NULL because that's what the field called 'process' contained when MySQL looked there for a value as it created the new record.
I do use this style for quick throw-away hacks involving known, secure data (e.g. a value supplied within the program itself). But for anything involving data that comes from outside the program or that might possibly contain other than [0-9a-zA-Z] it will save you grief to use placeholders.