So I have this function add_log:
function add_log($username, $action) {
$l_con = new con();
$log_action = $l_con->connect();
// IP to put in database
$ip_orig = $this->getIP();
$newa_ip = ip2long($ip_orig);
$prepara = $log_action->query("INSERT INTO log VALUES ('$username',
'$action', '$newa_ip', CURDATE(), NOW())");
}
When I use it in my register form it works perfectly and inserts in the database. But in the login script or anywhere else it doesn't work. I even tried putting weird names I was SURE I didn't use. I tried using it outside of the login script and still nothing.
First, you are missing optional column declarations within your SQL statement. Normally you would define them as:
INSERT INTO table (COLUMN1, COLUMN2, COLUMNN) VALUES ('a', 'b', 'n...');
Also, when using ip2long, be aware there is an alternative where you could be doing it directly in your SQL statement:
INSERT INTO log VALUES ('$username', '$action', INET_ATON('$new_ip'), CURDATE(), NOW())
To retreive, you can do long2ip or within your SQL, SELECT INET_NTOA(IP) as IP ...
Make sure there are no quotes in $username or $action as it will break the query. Also, I'd suggest using PDO or something similar, it would make any quotes irrelevant.
Related
I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.
Hopefully a simple fix but has been stumping me all weekend.
I have a simple script to connect to my MYSQL databse, then using fields from an HTML form enter a new record into the database.
The script is working just fine, but I have not defined the database columns in the script, simply used insert into and then referenced the VALUES as the HTLM form fields.
WORKING
mysql_select_db("golfingdb", $con);
mysql_query("INSERT INTO Test1
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
mysql_close($con);
NOT WORKING
mysql_select_db("golfingdb", $con);
mysql_query("INSERT INTO 'Test1' (First Name, Surname, Email)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
mysql_close($con);
However when I reference the database field names in the code then it fails to make a new record.
I have triple checked the spelling (including capitals) of the field names and it doesn't throw up any syntax errors.
Any help would be greatly appreciated.
Cheers
Paddy
You need to surround column names with backticks if the name contains a space.
(`First Name`,
Maybe it is the two word column name. You can use `First Name` or something like that when referencing the column.
Could you post the exact error MySQL gives you?
Try this
$firstname=$_POST["firstname"];
$lastname=$_POST["lastname"];
$email=$_POST["email"];
mysql_query("INSERT INTO Test1('First Name', 'Surname', 'Email')
VALUES ('$firstname','$lastname','$email')");
Make sure you have created the table structure with the right data types and lengths.
Backstick characters `` should be used to escape table and column names. Single quotes characters '' should be used to escape string values.
In your second example, the table name is escaped with single quotes instead of backsticks. In addition, the field names are not escaped at all, which probably causes a problem with the first field name that contains a space.
The correct form would be:
mysql_query("INSERT INTO `Test1` (`First Name`, `Surname`, `Email`)
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[email]')");
It's also important to note that PHP's mysql_ functions have been deprecated. It's highly recommended to use one of the alternatives as discussed in Why shouldn't I use mysql_* functions in PHP?
I have tried and it doesn't grow my database. Here's the code:
<?php
// Connecting to Ganoderma genome database
include('../utils/config.php');
// Inserting new data into the table
$sql = "INSERT INTO $var2 ('$column_id', '$column_name', '$column_seq') VALUES ('$_POST[id]', '$_POST[name]', '$_POST[seq]')";
// Qualifying successful entry
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Bioinformatician,
Aizek
I'm trying to write a User Login System for my website. I'm running WAMP on my laptop and using Aptana for development. I've been stuck trying to get a User Creation function to work for about 3 days now. This function here:
function create_new_user($email, $pass, $level){
$db = new PDO('mysql:host=localhost;dbname=jadams', 'root', '');
$insertQuery = "INSERT INTO jadams.user VALUES ($email, $pass, $level);";
$db->query($insertQuery);
return TRUE;
}
I have rewritten this function several times, using prepared statements and various forms of conditional checks, this is just the simplest one in the hopes of figuring it out. No matter what I try I cannot get the insertion into the database to work. I have gotten this login function working by forcibly inserting users through phpMyAdmin:
function is_pass_correct($email, $pass){
$db = new PDO('mysql:host=localhost;dbname=jadams', 'root', '');
$email = $db->quote($email);
$selectQuery = "SELECT password FROM jadams.user WHERE email = $email;";
$rows = $db->query($selectQuery);
$db=NULL;
if($rows) {
foreach ($rows as $row) {
if($pass === $row["password"]) {return TRUE;} //MD5
}
}
return FALSE;
}
The structure of my Database is email varchar(256) not null primary, password varchar(256) not null, access int; I have also tried the query with and without a semicolon.
You're missing the column names in which to insert the values.
"INSERT INTO jadams.user (email, password, level) VALUES ($email, $pass, $level);"
Also, since you're using the PDO library consider using prepared statements to escape untrusted data.
$insertQuery = "INSERT INTO jadams.user (email, password, level)
VALUES (:email, :password, :level)";
$db = $conn->prepare($insertQuery);
$db->execute(array(':email'=>$email,
':password'=>$pass,
':level'=>$level));
Are you getting an error?
It's hard to diagnose without knowing the full DB structure, but at first blush it looks like maybe the columns in that table do not match up with the values you provide.
Technically, the column names are not required, but if you do not supply them then you must have appropriate values for each column in order. If there is a userID or other field that you are not setting, that could be the issue.
From the manual:
If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list or the SELECT statement.
To be on the safe side, I would suggest explicitly setting the column names like so:
INSERT INTO
jadams.user (email, password, level)
VALUES ($email, $pass, $level)
Personally I prefer the INSERT INTO ... SET syntax. It feels more readable and less prone to mixing up columns.
INSERT INTO
jadams.user
SET
email = $email,
password = $password
level = $level
Of course, this doesn't get into parameter binding, password storage, and a whole host of other issues you'll also want to be thinking about.
It's also possible that the semicolon at the end of your query is causing an issue. I know for the old mysql_* functions the manual explicitly stated that you should not have a semicolon at the end of a query. However, there's nothing about that in PDO. I assume it's fine to have a semicolon at the end now but I would try removing it and see what happens. (Probably nothing).
I'm having problems with an INSERT statement, and the error only says:
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 '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)
I have a page that gets a couple of variables from the url through a php GET method. The address would be
sampledomain.com/sample.php?id=11&in=16&lang=1
Then I use $in = $_GET['in']; and $id =$_GET['id']; to get the values.
Now, I have a MySQL statement like this:
mysql_query("INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable') ") or die(mysql_error());
It just doesn't work even though the $in value is correct (I checked that). What's really strange is, when I put $id (or any numeric value) instead of $in, it inserts it! Both $id and $in are numeric, out of desperation I tried using $in_num = intval($in) and then inserting $in_num but no luck. No error is thrown.
The $some_variable part is irrelevant to this problem, the statement behaves the same with or without it.
This is a real conundrum for me, why would the statement work for one variable but not the other?
Yeah, I have ['in'] on the page, I mistyped it here.
that's the problem.
the only your problem.
it is obvious that nothing mysterious in a variable name, expecially when this variable gets interpolated and do not interfere with SQL at all.
thus, the only possible reason left - the typo again.
And as you fail to post the correct code here, it is become impossible to even find that typo for you. You have to do it yourself.
The only thing you can do to help yourself is to print out each interpolated variables and compare them.
Instead of silly one-liner a sane programmer would separate his code into several lines for the better readability/maintainability:
$sql = "INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
thus you can comment out the actual query execution and print the query out instead, for the debugging purposes.
And thus you'll be able to see yourself, if there is any difference in a variable names.
$sql1 = "INSERT INTO tagovi_rel (column1, column2) values ('$in', '$some_variable')";
$sql2 = "INSERT INTO tagovi_rel (column1, column2) values ('$id', '$some_variable')";
var_dump($sql1==$sql2,$sql1,$sql2);
first of all $in = $_GET[in']; has to be $in = $_GET['in']; you forgot a quote, and also in php when you do '$in' the result will be (STRING) $in but when you put "$in" then you will get the value of the variable.
Secondly try
mysql_query("INSERT INTO tagovi_rel (column1, column2) values (".$in.", ".$some_variable.") ") or die(mysql_error());