PHP & SQL inserting into a database table error - php

I'm slowly progressing through PHP and SQL and have stumbled upon a small error, when trying to send a string into an SQL database. What I'm trying to do is insert a users's detail into one table (which currently works) and send the user name along with 5 blank entries into another table. The table examscore fields are username, exam, exam1, exam2, exam3, exam4 (it is these exam fields that I require blank for now).
The problem is that I receive the following message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\E-LearningWebsite\addcustomertodb.php on line 11 (which line that starts $query1)
If possible could anyone explain what this error means and what i have done wrong?
<?php
require "dbconn.php";
$username = $_GET['username'];
$email = $_GET['email'];
$pass = $_GET['password'];
$query = "INSERT INTO customer VALUES ('".$username."','".$email."','".$pass."')";
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
$results = mysql_query($query) or die (mysql_error());
$results1 = mysql_query($query1) or die (mysql_error());
?>
Kind regards Andy

change
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
to
$query1 = "INSERT INTO examscores VALUES ('".$username."','','','','','')";
ps. you are inviting SQL injections but that is a different story...

The goggles! They do nothing! The sql injection vulnerabilities! And it's only Monday!
Why not just
$query ="INSERT INTO customer VALUES ('$username', '$email', '$pass');";
$query1 = "INSERT INTO examscores VALUES ('$username', '', '', '', etc...);";
PHP will happily replace $vars inside "" quoted strings for you. There's absolutely not need for all the concatentation you're doing. Any decent code editor will still highlight the vars for you.

you are missing dots to concatenate your strings
$query1 = "INSERT INTO examscores VALUES ('".$username."','"."','"."','"."','"."','"."')";
furthermore you dont need to have different strings
and still further more you dont need to include every column if you are not inserting them

Your immediate problem causing the errors is the missing .s from query1 from between the double-doublequotes, (or you should just delete the double-doublequotes altogether. Or even the unneeded columns...).
But there are way bigger issues in your code:
SQL injection: your code is vulnerable. You should at least escape th variables coming from the user...
mysql_* deprecation: as of PHP 5.5, these functions will be deprecated. Use either Mysqli or even ebtter PDO.

Related

Column count doesn't match value count at row 1 (columns and values are equal)

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.

PHP MySQL INSERT statement syntax error

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 :)

PHP Mysql multiple insert with foreach not working

Here is my code - I'm attempting to attach a bunch of user_id 's to a piece of content.
if (empty($errors)) // If everything's OK.
{
foreach($_POST['userId'] as $row)
{
$query = " ('".$row[learner_id]."', '".$postId."', '".$id."' ),";
}
$query = substr_replace($query,"",-1);
$mysql_return = mysqli_query("INSERT INTO subs (userId, postId, account_id ) VALUES ".$query) or die(mysql_error());
}
Would love any help you could give - it's not working...
And how's it not working? Syntax error? Silently puking? You're not escaping your POST data, so if any of those contain at least one single quote, that'll cause a syntax error right there, plus leaving you wide open for sql injection attacks.
Or maybe a foreign key check is failing... many possibilities, but you haven't given us nearly enough info to tell. What error message(s) are you getting?
Ok, I see several issues:
You are not using parameters or escaping, opening yourself up WIDE to sql injection attacks. See mysqli_real_escape_string.
What are you possibly sending to $_POST['userId'] that would make itself an array?
Unless learner_id is a constant, then this is a syntax error. If it is an array key, put it in quotes.
Where are $postId and $id coming from ?
The first parameter to mysqli_query is the identifier returned by mysqli_connect, whereas you're just giving it the query directly.
It should be like this,
$link = mysqli_connect("host", "user", "pass", "db");
$mysql_return = mysqli_query($link, "INSERT INTO subs (userId, postId, ac...

Sending a slash through mysql

I'm not sure why this has stumped me. I have the following code
$website = "http://www.google.com";
$name = "Person";
if(!empty($website) {
$name = "[url=$website]$name[/url]";
}
Then i try to insert that into mysql. I tried adding mysql_real_escape_string to both $website and $name (after the if statement), thinking the "/url" might also cause problems.
$name = mysql_real_escape_string($name);
Still no luck though. Any advice? What am I missing? It's giving me this error
"Parse error: syntax error, unexpected '/', expecting T_STRING or T_VARIABLE or T_NUM_STRING"
try
if(!empty($website)) {
$name = "[url={$website}]{$name}[/url]";
}
then use,
mysql_real_escape_string ($name);
This is a PHP syntax problem.
The parser thinks $name[ is the start of a array reference you have to add curly bracelets to tell the parser where the variable name starts and end:
"[url={$website}]{$name}[/url]"
There wont be any problem at all. When reading from database you should then put stripslashes() around your value.
e.g.
$query = "SELECT field FROM table";
$row = mysql_fetch_array(mysql_query($query));
echo(stripslashes($row['field']));
And your output will be the same like YOUR input.
Make sure you're quoting values you send into a query, like so:
$sql = "INSERT INTO table (column) VALUES ('$value')";
Whatever is in $value gets passed into the query. If you leave out the quotes, bad things may happen even if you use mysql_real_escape_string(). Inside strings, forward slashes do not have any special meaning in MySQL, and so mysql_real_escape_string() leaves them intact. This is not a bug, but the documented, correct behaviour. Basically, you need to quote all values in your query.
However, the best solution IMHO is to use PDO and its parametrized queries instead of the mysql_XXX API. It's a bit more complicated (not much though), and it allows you to pass parameters into a query through an associative array, doing all the escaping and quoting you need for you.
Are you putting quotes around the value you want to insert? This will work
INSERT INTO table_name (column_name)
VALUES ('[url=$website]http://www.google.com[/url]')
This will fail
INSERT INTO table_name (column_name)
VALUES ([url=$website]http://www.google.com[/url])
So you might have in you php
$query = "INSERT INTO table_name (column_name) VALUES ('$name')";
// DO MYSQL_QUERY

Run MySQL INSERT Query multiple times (insert values into multiple tables)

basically, I have 3 tables; users and projects, then I have 'users_projects' to allow the one-to-many formation. When a user adds a project, I need the project information stored and then the 'userid' and 'projectid' stored in the usersprojects table. It sounds like its really straight forward but I'm having problems with the syntax I think!?
As it stands, I have this as my INSERT queries (values going into 2 different tables):
$projectid = $_POST['projectid'];
$pname = $_POST['pname'];
$pdeadline = $_POST['pdeadline'];
$pdetails = $_POST['pdetails'];
$userid = $_POST['userid'];
$sql = "INSERT INTO projects (projectid, pname, pdeadline, pdetails) VALUES
('{$projectid}','{$pname}','{$pdeadline}','{$pdetails}')";
$sql = "INSERT INTO users_projects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: frontview.php");
exit();
You simply forgot to execute the sql between each query. Add the
mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
between each query and you are supposed to be fine.
b.t.w (1) it always helpful to test with a console open with tail -f on the sql log (under /var/log/mysql/ )
b.t.w.(2) You are having heavy security issues in your code.
b.t.w (3) You might want to consider using PDO/Mysqli and not the old mysql extension.
b.t.w (4) It would make your life simpler to use some kind of wrapper (a good class) to approach the DB and not do it directly everywhere in your code.
Yeah, two things I would check would be
1) are the queries being executed? Like the other poster mentiond, are you executing the SQL queries in between setting the SQL?
2) if you print/debug/display somehow the variables that you are inserting, are they getting populated? If you're seeing things get inserted, but some of the data is blank then something might be blowing up before that and those variables would be blank.
I may be misunderstanding but are you putting header("Location: main.php"); in the middle of you script?
$projectid=mysql_insert_id($connection);
I called this after my first query, this will get the AutoIncrement value from your projects table and store it in $projectid, then the second query will use it.
so after execution of my first query, I put the above code there, without changing anything else!!
You seem to be trying to execute mysql_query() only once. You have two queries, so it needs to be used twice, once on each query:
$sql = "INSERT INTO projects (projectid, projectname, projectdeadline, projectdetails) VALUES
('{$projectid}','{$projectname}','{$projectdeadline}','{$projectdetails}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
$sql = "INSERT INTO usersprojects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
Alternatively, you could use mysqli_multi_query(), but that might require a significant rewrite of your code to use the mysqli interface.

Categories