My MySQL query doesn't work, nothing goes to the database - php

I am trying to put a single article to the database, but fail:
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("easy_db",$con);
mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author) VALUES($title, $data, $topic, $author)");
mysql_close();
I checked the spelling and printed all the variables ($title, $data, $topic, $author), that I got from the post-http..
Nothing is being inserted to the database with that statement. Why?
UPDATED
I have got an error in this one too:
= mysql_query("SELECT page FROM `easy_db`.`article` ORDER BY article_id DESC LIMIT 1") or die(mysql_error());

Use an error checking statement after your query, so you know what's going wrong. Also, beware of SQL INJECTION, and put single quotes around your values:
$con=mysql_connect("localhost","root","") or trigger_error(mysql_error());
mysql_select_db("easy_db",$con);
$title = mysql_real_escape_string($title);
$article = mysql_real_escape_String($article);
$topic = mysql_real_escape_string($topic);
$author = mysql_real_escape_string($author);
mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author)
VALUES('".$title."', '".$data."', '".$topic."', '".$author."')")
or die ('Error: '.mysql_error());
// mysql_close(); this is not necessary, though

Please replace
mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author) VALUES($title, $data, $topic, $author)");
with
mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author) VALUES($title, $data, $topic, $author)") or die(mysql_error();
And try again. If there is an error, tell us. Be sure that you of your variable where you got it.
You should use the global variables $_POST and $_GET.

As this question is an exact duplicate of thousands already answered others (but never be closed though), I am going to point out to one somewhat different thing.
It seems everyone in the world are writing SQL errors into the browser and even killing their scripts in the middle of execution. Leaving the user with a cyphered message and no controls, yet providing a potential attacker with quite useful information. And at the same time leaving programmer totally ignorant of the errors occurred on the site. Funny, eh?
That's the dark side of PHP language in general, which suffer from terrible code examples spread over the world and is a bad side of this site of Stack Overflow as well, as it takes huge part in spreading these bad practices, wrong code, ridiculous habits and weird superstitions.
Because answer quality will never affect its rep points. So, one can write any nonsense and it will be upvoted, accepted, and copied further.
So, if you want to make your code a little better - never use die(). In case of running queries use trigger_error() instead, it will populate the error information according to current PHP settings: on a test server it will go onto screeen, but on a live server it will be logged for the site programmer. And it won't kill your script.

You have no single-quotes around your VALUES('val1', 'val2'...) variables::
mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author) VALUES('$title', '$data', '$topic', '$author')");
You should check the success of the query like:
$result = mysql_query("INSERT INTO easy_db.article (Title, Article, Topics, author) VALUES('$title', '$data', '$topic', '$author')");
if (!$result) {
echo mysql_error(); // find out what went wrong...
}
We don't see the rest of your code, but please be sure you have also sanitized all your input variables from $_POST using mysql_real_escape_string():
$title = mysql_real_escape_string($_POST['title']);
// etc...

Most likely you've forgotten to quote your inserted data. The query should look more like:
INSERT ... VALUES ('$title', '$data', '$topic', '$author')
and your code should be:
$result = mysql_query(...) or die(mysql_error());
Had you had the 'or die()' portion included, you'd get a syntax error from mysql telling you why the query failed. It is almost never a good idea to NOT check for error conditions after running a query. Even if the SQL is syntactically perfect, there's far too many other reasons for a query to fail to NOT check.

Related

saving information to database from webform

$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW())";
$query = "INSERT INTO address ". "(house_number,street_name,town/city,postcode,province/county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county', NOW())";
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
So I can create a connection to my database no problem and on my previous page I can send username and password to the database but then I come to the user details page to save the information and continually getting Invalid query 2 error. The table names are correct (users & address) and all variables are spelt correctly. Does anyone have a suggestion to fix the issue or a better alternative (I mean to just point me in the right direction of the research I should be looking at if I am way off target, if I have just mispelled something or have something in the wrong place then I would appreciate the heads up, have been at this quite a while now)
This is the code from the previous page and it works fine and sends the information to the database:
$query = "INSERT INTO login ". "(username,password) ". "VALUES('$uname','$epass', NOW())";// sets up sql query
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
mysqli_close($conn); // close database connection
As far as I know all the database side of things is fine, all data types are varchar except for dob which is date (I have tried changing this to varchar to see if it fixed the problem but it didnt) and userID is int and is an autoincrement for the unique primary key. I have also tested the php file without the validation rules and still gives the same error.
Quite a few things wrong here.
First you are reassigning the variable $query; so the first insert will be getting overwritten by the second, you need to concat the variable.
Then you have 2 queries you are attempting to send at one time. However you never tell Sql you've finished your first before starting your second.
Try the following instead take note Of The semi colons ; at the end of each.
You are also putting slashes into your column names which is illegal.
Lastly, you've got more values to insert than you have columns. Remove the now() from the end.
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email');";
$query .= "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county');";
Although this will now work, I highly recommend you do some research regarding safe practices with Sql.
Here would be a great starting point https://www.w3schools.com/php/php_mysql_prepared_statements.asp
On a side note, why are you concating your Strings? There's no need
$query = "INSERT INTO users (first_name,last_name,dob,mobile_number,landline_number,email) VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW());";
Maybe it's the fact that you are closing the connection after your first call.
try or die(mysqli_error($conn));
EDIT:
Delete passing value "NOW()".
code:
$query = "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county')";

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.

SQL Insert and Submit

When I execute this query it returns false, which means the query is wrong. Can you figure out why?
$string1 = 'wee';
$string2 = 'wee';
$string3 = 'wee';
$string4 = 'wee';
if (isset($_POST['submit'])) {
$query = "INSERT INTO data (book, title, content, author)
VALUES ($string1, $string2, $string3, $string4)";
mysql_query($query, $con);
}
However, when I put something that is like the following, it returns true and inserts correctly:
$query = "INSERT into data (book, title, content, author)
VALUES ('wee', 'wee', 'wee', 'wee')";
And another question: when I submit, it seems that the query is returning twice when executed which means two records with one query. Does anyone understand that?
If you need more information, just ask.
Thanks in advance.
Although this question seems answered, you should not be using user input directly in queries as this opens holes for vulnerabilities like SQL Injection (and that's bad mmmay)
If you look at the mysql page on php.net (mysql_query) the page says it is recommended you use an abstraction layer like PDO (pdo-mysql)
Using PDO will allow you to bind parameters to your sql queries to bypass the security implications of using user input in your queries.
If you don't bind parameters to your queries, you're gonna have a bad time.
Your field data type is string or varchar so you need to put '' or "" around them.
Change your query as below
$query = "INSERT into data (book, title, content, author)VALUES ('".$string1."', '".$string2."',
'".$string3."', '".$string4."')";
To resolve submit issue, please post your html code

Insert not working in MYSQL

Am trying to write a new record using the jquery function.
$.post("insertuser.php",$("#rohanStart").serialize(),function(data){
alert(data);
});
This seems to work and i do get an alert with the echo'ed statmenet. Problem is the values are not getting written into the database. Is there something wrong in the Query Statement?
mysql_query("INSERT INTO ajax_demo1( FirstName,LastName,Unit,Group,photo)
VALUES (
'".$arr['FirstName']."',
'".$arr['LastName']."',
'".$arr['Unit']."',
'".$arr['Group']."',
'".$arr['photo']."'
)");
echo $arr['Group'];
First don't use jQuery or any frameworks, they rely on the proprietary Microsoft JScript innerHTML method which does not work correctly with the DOM thus adding huge amounts of ambiguity in scripting.
Secondly you're NOT correctly escaping data going in to the database, that is a serious security issue.
Thirdly your approach to database queries is not taking error handling in to account, you're just dumping queries directly in and hoping for the best.
You should ALWAYS number your queries and enclose them as I have below. Note that besides errors it is good to fail conditions up-front however with database structure you should execute if successful first and THEN fail to increase your indentation (by a single space, not this tab waste where you have five screens to horizontally scroll) so you can visualize where you are in your own code.
$query1 = "SELECT * FROM table_name WHERE something='value'";
$result1 = mysql_query($query1);
if ($result1)
{
$row1 = mysql_fetch_assoc($result1);
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
If your main header includes (you DO have a main header being included for all requests except AJAX correct?) you should have a universal MySQL error handling function that you can use to log SQL errors.
The following is the universal database error handler. You should have administrative error logs for HTTP, JavaScript, PHP and SQL errors so you can review and correct issues that your visitors encounter instead of if they only inconvenience you.
function mysql_error_report($q,$e,$f)
{
if (isset($_SESSION['database']))
{
if (isset($_SESSION['id_member'])) {$id = $_SESSION['id_member'];} else {$id = 0;}
if (isset($_SESSION)) {$session = mysql_real_escape_string(session_id());} else {$session = 0;}
$ip = mysql_real_escape_string(getenv('REMOTE_ADDR'));
$query = mysql_real_escape_string($q);
$error = mysql_real_escape_string($e);
$function = mysql_real_escape_string($f);
if (isset($_SESSION['type'])) {$type = mysql_real_escape_string($_SESSION['type']);} else if (isset($_SESSION['cms_browser'])) {$type = 'Browser';} else {$type = 'Unknown';}
if (isset($_SERVER['REQUEST_URI'])) {$url = $_SERVER['REQUEST_URI'];} else {$url = '';}
if (isset($_SERVER['HTTP_USER_AGENT'])) {$ua = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);} else {$ua = '';}
$query1 = "INSERT INTO log_errors_sql (id_session, type, id_user, date, ip, function, mysql_error, mysql_query, url, user_agent) VALUES ('$session', '$type', '$id', NOW(), INET_ATON('$ip'), '$function', '$error', '$query', '$url', '$ua')";
$result1 = mysql_query($query1);
if (!$result1) {mysql_error_report_mail($q,$e,$f,$ua);}
}
else {mysql_error_report_mail($q,$e,$f);}
}
By using that approach you'll strengthen your coding practices to be much stricter. You don't want ambiguity, you want to be a total tightass about your code because the less subjectivity there is in your coding the more your code will be able to handle.
Also your white-space is very loose.
This...
INSERT INTO ajax_demo1( FirstName,LastName,Unit,Group,photo)
Should be formatted like this...
INSERT INTO ajax_demo1(FirstName, LastName, Unit, Group, photo)
You might ask why keeping your white-space like that is important, if you haven't spent a ton of time with find and replace (look up "Advanced Find & Replace", it works on wine/Linux and blows the crap away out of the native Linux console command performance wise and it's dirt cheap, supports regex, etc) you'll find yourself making mass site-wide edits in the blink of an eye because even your white-space is uniformly the same strict approach.
Should you heed my advice use a AFR (Advanced Find and Replace) to search for (but not replace) all instances of "mysql_query" and correct the formatting of everything you've written. Mix in a little AJAX notifications and you can see the errors instantly while you're still in the browser without a single alt-tab. That's how I roll.
...and of course doing this will make your debugging much easier. This isn't a fish, this is fishing and I hope it helps.

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...

Categories