I'm trying to insert remote POST data (articles sent by iSnare) into MySQL with PHP. Data comes successfully from remote POST sender and I can write it to plain-text file without a problem.
Unfortunately, when it comes to insert it into MySQL, MySQL cuts off string (article) at special char. I tried many things but still I'm unsuccessful!
I tried:
Escaping chars with mysql_real_escape_string()
Using htmlentities() and htmlspecialchars() (with every parameter..)
Sending SET NAMES utf8 query to MySQL before doing everything else
All tables and columns are UTF-8 encoded and utf8_general_ci (also tried utf8_unicode_ci and utf8_bin as collation)
Saving all PHP files as UTF-8
Still I couldn't find the solution. I will appreciate it very very very much if someone can help me solve this problem.
Here is my table definition and PHP codes:
PHP
function guvenlik_sql($x){
// Cleans inputs agains sql injection
return mysql_real_escape_string(htmlentities(stripslashes($x)), ENT_QUOTES);
}
// Check if data really comes from an Isnare.com server (Address hidden)
if ($_SERVER['REMOTE_ADDR'] == $isnareIP || $_SERVER['REMOTE_ADDR'] == "xxx.xxx.xxx.xxx") {
$title = guvenlik_sql($_POST["article_title"]);
$first_name = guvenlik_sql($_POST["article_author"]);
$description = guvenlik_sql($_POST["article_summary"]);
$category = guvenlik_sql($_POST["article_category"]);
$article = guvenlik_sql($_REQUEST["article_body_text"]);
$article_html = guvenlik_sql($_POST["article_body_html"]);
$resource_box = guvenlik_sql($_POST["article_bio_text"]);
$resource_box_html = guvenlik_sql($_POST["article_bio_html"]);
$keywords = guvenlik_sql($_POST["article_keywords"]);
$email = guvenlik_sql($_POST["article_email"]);
$fp = fopen('test.txt', 'a');
fwrite($fp, $title."\n");
fwrite($fp, $article."\n\n\n\n");
fclose($fp);
mysql_query("INSERT INTO articles " .
"(" .
"first_name, " .
"email, " .
"title, " .
"description, " .
"article, " .
"article_html, " .
"category, " .
"resource_box, " .
"resource_box_html, " .
"keywords, " .
"distributor, " .
"distributor_host" .
") VALUES (" .
"'$first_name', " .
"'$email', " .
"'$title', " .
"'$description', " .
"'$article', " .
"'$article_html', " .
"'$category', " .
"'$resource_box', " .
"'$resource_box_html', " .
"'$keywords', " .
"'$isnare', " .
"'$_SERVER['REMOTE_ADDR']', " .
")") or die(mysql_error());
} //end if security
Table definiton
CREATE TABLE `articles` (
`article_ID` int(11) NOT NULL auto_increment,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`author_url` varchar(255) NOT NULL,
`company_name` varchar(100) NOT NULL,
`address1` varchar(100) NOT NULL,
`address2` varchar(100) NOT NULL,
`state_2digit` varchar(100) NOT NULL,
`state` varchar(100) NOT NULL,
`zip_code` varchar(100) NOT NULL,
`country` varchar(100) NOT NULL,
`phone` varchar(100) NOT NULL,
`newsletter` varchar(100) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`article` longtext NOT NULL,
`article_html` longtext NOT NULL,
`category` varchar(100) NOT NULL,
`cat` varchar(100) NOT NULL,
`resource_box` text NOT NULL,
`resource_box_html` longtext NOT NULL,
`keywords` varchar(255) NOT NULL,
`publish_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
`distributor` varchar(255) NOT NULL default '',
`distributor_host` varchar(255) NOT NULL,
PRIMARY KEY (`article_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC
I've just dealt with the same situation, entries were cut off where the special character (ä, ö, è, etc) supposed to be. All my files are UTF8 encoded, the connection is UTF8 encoded, table collations are UTF8, still the entries were cut off.
My solution was: even more UTF-encoding! :) Use utf8_encode() on the entries which can contain special characters.
mysql_query("INSERT INTO articles (first_name, email, title, description, article, article_html, category, resource_box, resource_box_html, keywords, distributor, distributor_host) values (
'" . utf8_encode($first_name) . "',
'" . $email . "',
'" . utf8_encode($title) . "',
'" . utf8_encode($description) . "',
// etc
Very late answer, but I came across this issue in one of our older projects. It turns out, that MySql has its own "implementation" of UTF8. It cannot save chars, which consists of more than 3 bytes (like emoticons etc.). Sometimes it throws error (like in this question "Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?) and sometimes it just cuts off the string.
The solution is switching from utf8 to utf8mb4 as described in linked question above, or make sure you cut off all long chars before saving.
I know this is an old question, but as we are using more and more emoticons, this can occur in some older apps. Hope it helps someone.
"Set names utf8" only sets the character set for table and column names, you have to use "set character set utf8" too, for the content character set.
Are you sure that the string is not cut off because of was longer than your column definition allows?
The problem could also be that the data is stored successfully in the database, but the application which you use to show the data from the database cuts off the displayed string. This mostly happens with strings containing null characters in windows-based applications since windows-controls use null-terminated strings internally.
1) put that sql string you're generating into a variable and write it to a file before you send it to MySQL (so you can look at exactly what is being sent)
2) mysqld has a setting "max_allowed_packet" which I think cuts off long queries.
3) you're passing ENT_QUOTES to mysql_real_escape_string(). I think you mean to pass it to htmlentities()
For those who might have the same problem and the answers before do not help, I got another suggestion: Check the CONTENT TYPE ! It should be like this:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
I had the very same probleme as Donald had - this did the MAGIC :) (I did not imagin that the colegue who worked on the file in the first place hadn't set it right...)
Just solved a similar issue. My problem was I was trying to insert Latin-1 encoded data into a UTF-8 encoded table. Double check the encoding of your data -- you are likely getting non-UTF-8 data from your input.
Using mysqli_set_charset is what saved the day for me:
$conn = new mysqli($host, $username, $password, $database);
mysqli_set_charset($conn, 'utf8');
Related
I have an existing table and I'm trying to insert data to it from a form submission.
I think I need another set of eyes to look over my code. There is an issue with it, at this point I'm not sure what.
I fill out the form, it appears to submit, I check the table and I get nothing. No data gets inserted.
If some of the values aren't being used right now, can that hinder the data from being inserted into the table? Shouldn't the form inputs that are on the form be inserted anyway? I tried to use only the values within the form, and that still did not work.
For example, right now the form inputs are only for first, last, title, genre, about, and picture. The rest only exist within the table. Data for the remaining fields cannot be currently entered at this time.
Hopefully someone has a solution?
$servername = "server";
$username = "user";
$password = "pass";
$dbname = "db";
if (isset($_POST['submit'])){
$conn = mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$first = mysqli_real_escape_string($conn, $_POST['First']);
$last = mysqli_real_escape_string($conn, $_POST['Last']);
$title = mysqli_real_escape_string($conn, $_POST['Title']);
$storylink = mysqli_real_escape_string($conn, $_POST['StoryLink']);
$genre = mysqli_real_escape_string($conn, $_POST['Genre']);
$about = mysqli_real_escape_string($conn, $_POST['About']);
$link = mysqli_real_escape_string($conn, $_POST['Link']);
$picture = mysqli_real_escape_string($conn, $_POST['Picture']);
$alt = mysqli_real_escape_string($conn, $_POST['ALT']);
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
mysqli_close($conn);
}
Here is one input field from the form. The others are pretty much the same.
<input type="text" id="ContrTitle" name="Title" placeholder="Title" class="inputFields" style="width:650px;" />
Could there be an issue with the name within the input?
sql table structure:
CREATE TABLE IF NOT EXISTS `ContrTemp` (
`ID` int(5) NOT NULL AUTO_INCREMENT,
`First` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Last` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`StoryLink` varchar(140) COLLATE utf8_unicode_ci NOT NULL,
`Genre` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
`About` varchar(2000) COLLATE utf8_unicode_ci NOT NULL,
`Link` varchar(125) COLLATE utf8_unicode_ci NOT NULL,
`Picture` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`ALT` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Now I'm actually hitting the database, a record shows up, but no data was inserted. Before, No record was inserted at all.
You can try this one for inserting data
$sql = 'INSERT INTO ContrTemp (First,Last,Title,StoryLink,Genre,About,Link,Picture,ALT) VALUES ("'.$first.'","'.$last.'","'.$title.'","'.$storylink.'","'.$genre.'","'.$about.'","'.$link.'","'.$picture.'","'.$alt.'")';
I think you have done pretty well but one last try put these symbols [backticks] ` around your fields to understand mysql they are just fields.
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
Your mysqli_error() is incorrect syntax, you need to specify the connection so have mysqli_error($conn) to properly feedback to you the SQL errors. As mentioned by Mitkosoft in comments some of your column names are MySQL keywords. It could be a good habit to get into to always encase column names in backticks.
So:
$sql = "INSERT INTO ContrTemp (`First`,`Last`,`Title`,`StoryLink`,`Genre`,`About`,`Link`,`Picture`,`ALT`)
VALUES ('$first','$last','$title','$storylink','$genre','$about','$link','$picture','$alt')";
mysqli_query($conn, $sql) or die('Error: ' . mysqli_error($conn));
Also you don't need to select db with mysqli_select_db($conn,$dbname); because the database is selected on the login command mysqli_connect above.
Further queries:
Is your database access account allowed to INSERT to this database?
Can you insert the same data as in your form directly into the database using an interface such as PHPMyAdmin, MySQL Workbench (Or whichever one you use to view the DB)?
I had hoped this had been as simple as the code I provided above, thus the reason I did not mention that this code was being used as part of a WordPress template. I did not think that would be come an issue as the template is pretty light weight.
With that said, I simply took my block of php code that handles the data insertion, and I placed it at the top of the template. Worked like a charm..
I wrote a php script to import a CSV file into a wordpress database. I have been working through lots of different errors today which were crashing the website till I fixed them.
Now all the errors are cleared and the string at the end of the function is being printed to the screen as if everything is ok but it is not entering my data to the DB.
Also for testing sake I removed the create DB part and only left the remove to see if it would remove the DB and it did not. So basically it appears my function does not have errors but it is being ran. Also it is not actually doing anything. I do not understand how it could run through the function telling me each time there is an error or a file path that does not exist but not actually carry out the operations I am trying to execute.
Any input on how to troubleshoot this or where to go from here would be appreciated,
function productsExec() {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
global $wpdb;
global $simple_prod_version;
$table_name = $wpdb->prefix . "wuno_inventory";
if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
$sql = "DROP TABLE IF EXISTS $table_name";
dbDelta($sql);
// $wpdb->query($sql);
$sql = "CREATE TABLE " . $table_name . " (
id int(8) NOT NULL AUTO_INCREMENT,
wuno-product varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-description varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-alternates varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-onhand varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-condition varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
dbDelta($sql);
// $wpdb->query($sql);
//Upload File
if (is_uploaded_file($_FILES['inventory.csv']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['inventory.csv']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['inventory.csv']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen(inventory.csv, 'w');
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
$insert = "INSERT INTO" . $table_name . "(wuno-product, wuno-description, wuno-alternates, wuno-onhand, wuno-condition)" .
"VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]')";
$results = $wpdb->query( $insert );
}
fclose($handle);
echo 'Everything seems to be running smoothly.';
}
}
As mentioned in comments, and as per OP's request:
INSERT INTO" . $table_name . " translates to, and for example INSERT INTOtablename since there is no space between INFO and "
Plus, you have hyphens for column names that MySQL is translating as wuno MINUS product, as a math equation and the same for the other column names.
Consult http://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html on Identifier Qualifiers
You can use hyphens, but ticks are required to be used around the column names.
$insert = "INSERT INTO " . $table_name . " (`wuno-product`, `wuno-description`, `wuno-alternates`, `wuno-onhand`, `wuno-condition`)
Edit:
I spotted something else.
$handle = fopen(inventory.csv, 'w');
There should be quotes around the filename:
$handle = fopen("inventory.csv", 'w');
as per the manual on fopen() http://php.net/manual/en/function.fopen.php
$handle = fopen("c:\\folder\\resource.txt", "r");
and error reporting would have thrown you a notice about it.
Plus, since you're using $_FILES, and if using a form, it should be a POST method and contain a valid enctype.
http://php.net/manual/en/features.file-upload.post-method.php
However, this seems invalid $_FILES['inventory.csv'] or is unclear.
Usually, the first array parameter is a matching name attribute. Consult the manual link just above.
Also add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I am trying to get what should otherwise be a simple but of php to insert sample data into a table, but something just isn't having any of it.
Table Definition:
CREATE TABLE IF NOT EXISTS teams (
token varchar(12) COLLATE utf8_unicode_ci NOT NULL,
tname varchar(48) COLLATE utf8_unicode_ci NOT NULL,
captain varchar(64) COLLATE utf8_unicode_ci NOT NULL,
email varchar(64) COLLATE utf8_unicode_ci NOT NULL,
phone varchar(14) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (token),
UNIQUE KEY name (tname),
KEY id (token)
)
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Code:
$con = mysqli_connect("localhost","username","password","database");
$tname = "Big Bang";
$cname = "Mike";
$cemail = "test#gmail.com";
$cphone = "123-456-7898";
$teamToken = strtoupper(bin2hex(mcrypt_create_iv(6, MCRYPT_DEV_URANDOM)));
$query = "INSERT INTO teams (token, tname, captain, email, phone) VALUES ('" . $teamToken . "', '" . $tname . "', '" . $cname . "', '" . $cemail . "', '" . $cphone . "')";
if (mysqli_query($con, $query))
{
echo "Pass!";
}
else
{
echo $query;
}
mysqli_close($con);
What's odd is the php echos the query, because the mysqli_query result is false, yet the echoed query, when copied and pasted right into phpMyAdmin's terminal, works fine.
I am at my qit's end.
Your Code:
$con = mysqli_connect("localhost","username","password","database");
Edited code:
$con = mysqli_connect("localhost","root","","database");
if(!$con):
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
endif;
Its worked fine on my localhost
Maybe the datatypes of our columns make any problems.
I have once a similar "error" where my token field was to short. phpMyAdmin simply cut the long string to fit (or some thing this) and so it worked inside phpMyAdmin but not with my program.
Please post the CREATE statement of your table.
Try this
mysqli_query($con, $query) or die(mysqli_error($con));
I will suggest go step by step
step 1 : $con = mysqli_connect("localhost","username","password","database");
comment everything other than this statement.
then below write
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
verify your username password and database name (by default:username=="root" password=="" )
step 2 : add the query statements and print it. also check that all values are within their bounds as specified id DB.
step 3 :if $con and $query are valid then you will get your o/p as you req.
If still you have an error please paste your error statement.
using following to connect:
username="root" password=""
Your code works fine in my system.
I used varchar as datatype. Maybe the length of the varchar which you have taken as 12 is less to store the $teamToken variable. Try increasing the size.
It might sound a bit confusing, and perhaps what I'm doing isn't right at all, but here goes.
Our users can upload .csv files containing their school's data, exported from an external management system called SIMS. Once they upload that file I want to run a .sql script that updates our database with the information they provide in this file. What I've done, on the upload file page (works like a charm), is create a session variable containing the file path and name of the uploaded file, as shown below (file path is blanked out):
$target_path = "xxx";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "<p>The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.</p>" ;
echo "<p><a href='sqltest.php'>Click here</a> to upload your files into the database.</p>" ;
$_SESSION['file'] = $target_path ;
}
Below is a portion of my .sql file operated within PHP containing the session variable. Because most of this populate script uses the same kind of commands throughout it will probably not make sense to show you all 973 lines of code (of course there is a session_start() active at the top of the page).
$filename = $_SESSION['file'] ;
mysqli_query($dbc, 'SET foreign_key_checks = 0') ;
$populate =
"CREATE TEMPORARY TABLE IF NOT EXISTS `mldb`.`TempSchool`
(
`CentreNo` INT UNSIGNED NOT NULL,
`School` VARCHAR(255) NULL,
`Street` VARCHAR(255) NULL,
`Town` VARCHAR(255) NULL,
`County` VARCHAR(255) NULL,
`Postcode` VARCHAR(10) NULL,
`Tel` VARCHAR(45) NULL,
`URL` VARCHAR(512) NULL,
`Email` VARCHAR(255) NULL,
`Headteacher` VARCHAR(255) NULL,
`LEA` VARCHAR(45) NULL,
`LEANo` INT UNSIGNED NULL,
`EstablishmentNo` INT UNSIGNED NULL,
`URN` INT UNSIGNED NULL,
`Governance` VARCHAR(45) NULL,
`Phase` VARCHAR(45) NULL,
PRIMARY KEY (`CentreNo`)
)
ENGINE = InnoDB ;
LOAD DATA INFILE '$filename'
IGNORE INTO TABLE `TempSchool`
FIELDS TERMINATED BY ' , '
OPTIONALLY ENCLOSED BY ' \" '
LINES TERMINATED BY ' \r\n '
IGNORE 1 LINES (etc...)
I'm getting an error on line 25 of the code (LOAD DATA INFILE '$filename') displaying the following:
Invalid query: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 'LOAD DATA INFILE
'C:/Users/Public/Dropbox/mlwebfiles/Trial/uploads/MarksLive Set' at line 25
Presumably it's got something to do with the fact that, even though it's recognizing the file path and file name stored in the $_SESSION['file'] variable, but it's not actually doing anything with it. Is there a way where this .sql file can operate with through PHP set up variables for the file names? Many thanks!
After searching long and hard, and far and wide we've found a (what we think is the only) solution: create a function to loop through every one of these 'mini-queries' individually and it seems to be a lot more happy now! We actually came across this suggestion before but we rejected it initially because it would (and did) take a lot of time to separate 973 lines of code to split all the individual database additions...
$populate =
"
CREATE TEMPORARY TABLE IF NOT EXISTS `mldb`.`TempSchool`
(
`CentreNo` INT UNSIGNED NOT NULL,
`School` VARCHAR(255) NULL,
`Street` VARCHAR(255) NULL,
`Town` VARCHAR(255) NULL,
`County` VARCHAR(255) NULL,
`Postcode` VARCHAR(10) NULL,
`Tel` VARCHAR(45) NULL,
`URL` VARCHAR(512) NULL,
`Email` VARCHAR(255) NULL,
`Headteacher` VARCHAR(255) NULL,
`LEA` VARCHAR(45) NULL,
`LEANo` INT UNSIGNED NULL,
`EstablishmentNo` INT UNSIGNED NULL,
`URN` INT UNSIGNED NULL,
`Governance` VARCHAR(45) NULL,
`Phase` VARCHAR(45) NULL,
PRIMARY KEY (`CentreNo`)
)
ENGINE = InnoDB ;
" ;
populate ($dbc, $populate);
$populate =
"
LOAD DATA INFILE '$path'
IGNORE INTO TABLE `mldb`.`TempSchool`
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\r\\n'
IGNORE 1 LINES
(#AdNo, #UPN, #ULN, #UCI, #CandidateNo, #LegalSurname, #LegalForename,
#PreferredSurname, #PreferredForename, #Gender, #DOB, #Email,
#InCare, #EverInCare, #FSM, #FSMEver6, #EAL, #SENStatus, #AMA,
#Attendance, #RegGroup, #YearGroup, #EnteredYearDate,
#Class, #Subject, #Staff, #Initials,
CentreNo, School, Street, Town, County, Postcode, Tel, URL,
Email, Headteacher, LEA, LEANo, EstablishmentNo, Governance, Phase)
" ;
populate ($dbc, $populate);
Yeah, I know, its common problem, but I cant solve it for last 3 hours.
I do this query:
$query = 'UPDATE `'.$masterapp_users_table.'` SET `login` = "'.htmlspecialchars(strip_tags($_POST['login'])).'", `pass` = "'.md5(htmlspecialchars(strip_tags($_POST['pass']))).'", `email` = "'.htmlspecialchars(strip_tags($_POST['email'])).'", `firstname` = "'.htmlspecialchars(strip_tags($_POST['fn'])).'", `secondname` = "'.htmlspecialchars(strip_tags($_POST['sn'])).'" WHERE `login` = "'.htmlspecialchars(strip_tags($_POST['previouslogin'])).'"';
echo $query.'<br />';
mysql_query($query) or die(mysql_error());
and I get this:
UPDATE `masterapp_users` SET `login` = "asdasdasd", `pass` = "a3dcb4d229de6fde0db5686dee47145d", `email` = "asdasdasd", `firstname`
= "asdasdasd", `secondname` = "asdasdasd" WHERE `login` = "88888881"<br />Unknown column 'login' in 'where clause'
But it changes the record!
Maybe someone can see what I cant see?
Oh! forgot to say: If I paste that string from browser to PMA, it works fine.
UPDATE:
CREATE TABLE IF NOT EXISTS `masterapp_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`firstname` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`secondname` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `login` (`login`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=33 ;
The error means that the column in the MasterApp_Users table is not called login; it is Login or LOGIN or log_in or user or username or user_name or ...
In the statement that constructs the string, you have back-ticks:
UPDATE `'.$masterapp_users_table.'` SET `login` ...
In the echo, those back-ticks aren't showing.
If you use back-ticks like that, the column names become case-sensitive. What was the spelling of the CREATE TABLE statement precisely? Were column names written in mixed case inside back-ticks?
...Now we have the table schema shown, it is less explicable (not that it was easily explained before)...
Are you sure your browser and your PHP are connecting to the same database?
To debug further, I suggest changing:
The WHERE criterion to specify the id column and an appropriate value.
Do not SET the login column.
Check whether the UPDATE changes what you expect it to change.
If it doesn't change the record you think it should (but it does work), you have an issue identifying the database.
If you end up with a different column not being found, we can be pretty sure that there's a different table altogether. Maybe do a SELECT * FROM masterapp_users and review the column definitions returned.
If it changes the record, then we have a deep mystery on our hands.
It changes the record.
The complaint was specifically about the login column in the WHERE clause. If you specify id in the WHERE clause, are you able to set login in the SET clause of the statement?
If so, this is beginning to look like a bug in the DBMS. It is difficult to see why it could complain about login in WHERE and not in SET. Thus, it is unlikely to be the solution.
If the message changes to something roughly equivalent to 'unknown column login in the SET clause', then there is some self-consistency.
What happens if you rename the column in the table and modify the code accordingly?
Resolution
Comment N:
If it allows SET login = ... and not WHERE login = ... in a single statement, then I think you've got a bug. I'm surprised; it isn't like a DBMS (any DBMS) to be quite that capricious, so I'd need to be very sure about it before calling it a bug. It may also mean there's another factor at play here. If you add an echo "Hi" after the mysql_query() or die line, does that get through? Are you in fact debugging the wrong bit of SQL? Maybe there's a SELECT or something afterwards that's malformed?
Comment N+1:
Yeah thanks! After I add echo 'Hi'; after mysql_query, it appeared, so the problem was in my next queries. I knew that the problem was stupid. facepalm
Who's never made a similar mistake?
If my query works in phpMyAdmin but not from the code, the first thing I do is change
SELECT `column` FROM `table`
to
SELECT `column` FROM `database`.`table`
, or similarly with UPDATE queries of course. Perhaps this is your fix, and the MySQL error is just a bit cryptic.
Edit:
Furthermore, do not use htmlspecialchars nor strip_tags for your query escaping! It is insecure because this is not intended usage. To escape query values, it's better to use mysql_real_escape_string. Use the correct escape function for the correct application. I would write your query as follows:
$query = '
UPDATE `' . $masterapp_users_table . '`
SET `login` = "' . mysql_real_escape_string($_POST['login']) . '",
`pass` = "' . md5($_POST['pass']) . '",
`email` = "' . mysql_real_escape_string($_POST['email']) . '",
`firstname` = "' . mysql_real_escape_string($_POST['fn']) . '",
`secondname` = "' . mysql_real_escape_string($_POST['sn']) . '"
WHERE `login` = "' . mysql_real_escape_string($_POST['previouslogin']) . '"
';
// To display it in your browser:
echo htmlspecialchars($query) . '<br />';
// To run it:
mysql_query($query) or die(mysql_error());
This is just a friendly lesson. Wrong escape functions can lead to serious security holes.