an issue with MySQL query - mysql

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.

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.

How to insert result of mysql_real_escape_string() into oracle database?

For inserting special characters in data like (,')etc., I am using mysql_real_escape_string() function & it's working fine.
Now I want to use same variable while inserting values in Oracle.
$str = 'N.G.Palace\'s Building',
'xyzcity', '12345678','India','100001',12
Here $str is result of mysql_real_escape_string(). so it escapes special character.
Now my code for oracle is like this-:
$qry ="INSERT INTO Ora_table(ship_to_street, ship_to_city,ship_to_country, ship_to_telephone, order_id, record_no) VALUES(".$str);
So my doubt is Oracle is not accepting values return by mysql_real_escape_string i.e. Palace\'s (like this as this mysql function attach \ before 'single quote)?
So can anybody tell me ho9w can I use that variable $str to insert data into Oracle?
Also I tried like this also-:
"q"."'"."c".$str."c"."'"
can we use this for multiple values like in my case...though still I am unable
to inser data in oracle?
HOW to insert special characters in Oracle db?
like 'SWEET/HOME', 'CROY-BOY' etc. /,-,\ etc.
please tell me..
I strongly urge you not to build queries by appending strings together. This is a ticket straight to hell - or to SQL Injection City, which is one stop earlier. :-) Seriously, though, if you use parameter markers and bind the values to the parameter markers you gain a couple of advantages:
You don't have to escape anything, and
No worries about SQL injection.
Share and enjoy.
From: http://www.php.net/manual/en/function.stripslashes.php#94758
function no_magic_quotes($query) {
$data = explode("\\",$query);
$cleaned = implode("",$data);
return $cleaned;
}
// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amazing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);
echo '<b>Without function:</b> '.$badstring;
echo '<br><br>';
echo '<b>With function:</b> '.no_magic_quotes($badstring);

Whats wrong with this MySQL Update Query?

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.

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.

Inserting data using PHP into mysql when it contains a '

I am writing lots of info from an XML file into a database.
Everything works fine until I come across a field with the ' in the description, that insertion fails with an error
Error
1064:You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'd like you to feel that way too.
We'd love to have you visit us to view
over 100' at line 3
Is there a way to have this inserted without it failing? the import file could be large and change regularly so I cannot search and replace ' characters within it.
My actual PHP Statement is:
$query = mysql_query("REPLACE into list
(id, name, link, description, cost, date_added,type,myipaq,private,imgurl)
VALUES ('$id','$name','$link',"'$description'",'$cost','$date','$type','$myipaq','$private','$imgurl')");
thanks in advance,
Greg
This falls under the category of SQL injection.
In PHP a function: mysql_real_escape_string is used to encode a string so that none of it can affect the SQL statement it might be concatenated into.
so make sure all of your values go through the mysql_real_escape_string function and you will be fine.
API REF: http://php.net/manual/en/function.mysql-real-escape-string.php
Just pass your data through mysql_real_escape_string()
Use my handy dandy function:
function mysql_safe_string($value) {
if(is_numeric($value)) return $value;
elseif(empty($value)) return 'NULL';
elseif(is_string($value)) return '\''.mysql_real_escape_string($value).'\'';
elseif(is_array($value)) return implode(',',array_map('mysql_safe_string',$value));
}
function mysql_safe_query($format) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
$query = vsprintf($format,$args);
$result = mysql_query($query);
if($result === false) echo '<div class="mysql-error"><strong>Error: </strong>',mysql_error(),'<br/><strong>Query: </strong>',$query,'</div>';
return $result;
}
Like so:
mysql_safe_query('INSERT INTO table VALUES (%s, %s, %s)', $val1, $val2, $val3);
And forget about quoting or not quoting your strings, and writing out mysql_real_escape_string a dozen times.
The only really safe way of inserting or replacing or indeed interacting with anything on a database with PHP is to use prepared statements. There really is no excuse anymore for doing it any other way. Escaping strings using mysql_real_escape_string will give you some protection, but it is not bullet proof.
Prepared statements are not even hard. See the PHP manual page on them, and there are several wrappers to make life even easier, personally I like the codesense mysqli wrapper a lot and have been using it for a while with no problems - it's no harder than straight MySQL PHP code. EasyPDO looks promising too.
You should check out the related question "PHP: Is mysql_real_escape_string" sufficient for cleaning user input" for further details as to why you shouldn't be lazy.
Use: php.net/manual/en/function.addslashes.php
Addslashes prevent's just that!
And if you use that, just use
http://www.php.net/manual/en/function.stripslashes.php
to remove slashes from your string!