mysql query insert issue - php

my query is not inserting and i'm not getting any errors. can't figure out why it's not inserting
foreach($_POST as $key => $value) {
$clean[$key] = mysql_real_escape_string($value);
}
if(isset($_POST['submit'])) {
$entry = "INSERT INTO test (Word, Type, Lang, Country, Gender, Advice, y_Advice, Notes,
EditorNotify, Equiv)
VALUES('".$clean["word_field"]."',
'".$clean["type_field"]."',
'".$clean["lang"]."',
'".$clean["Country"]."',
'".$clean["gender"]."',
'".$clean["advice"]."',
'".$clean["y_advice"]."',
'".$clean["Notes"]."',
'".($clean["Notes"] != '' ? '1' : '')."',
'".$clean["Equiv"]."')";
echo mysql_query ($entry);
mysql_query ($entry);

You're actually doing the insert twice because of this:
echo mysql_query ($entry);
mysql_query ($entry);
The echo line will run the query, and so will the line after it. You need to get rid of that. (though I guess you only put it in there for testing purposes?)
Instead of that, I'd suggest just echoing $entry itself, so you get to see the finished SQL string. You may spot something wrong with the query right away just from that.
If you don't, then try copying+pasting that string into a SQL query program to see what the actual error is. That'll allow you to play with the query until you get it right.
You could also use the PHP command mysql_error() to get the error out of PHP, but it's when you've got a weird SQL error, it can often be quicker and easier to play with the query directly rather than within the PHP code.
hope that helps.

Try replacing:
(Word, Type, Lang, Country, Gender, Advice, y_Advice, Notes,
EditorNotify, Equiv)
With:
(`Word`, `Type`, `Lang`, `Country`,`Gender`, `Advice`, `y_Advice`, `Notes`,
`EditorNotify`, `Equiv`)

You don't know whether you're getting any errors. First, get rid of echo mysql_query(). Then run:
mysql_query($query) or die(mysql_error());
If mysql_query() returns false, which it does upon failure, whatever MySQL error the query generated will now be printed to the screen.
Just a minor note: you should initialize $clean with $clean = array();
If the problem is that the conditional is not firing, then the problem may be elsewhere. Do you have an <input> named "submit" in your form, and is the method of the form post?
Query itself looks okay to me. I think it is difficult to read, so I would do this, but that's just personal style:
$notify = $clean['Notes'] != '' ? '1' : '';
$query = <<<SQL
INSERT INTO test
(Notes, EditoryNotify)
VALUES
($clean[Notes], $notify)
SQL;

Related

PHP & Mysql Syntax incorrect?

I am having an issue with this not running at all when the information is submitted, I believe that I have the syntax wrong.
if ($_POST['note'] != $player->note_text) {
$message = 'Admin '.$user.' has added the note ('.$_POST['note'].') to '.$player->name.'('.$pid.')';
logIt($user, $message, $dbcon);
$note = $_POST['note'];
$note = '"'.$note.'"';
$UpdateN = "INSERT INTO notes (uid, staff_name, name, alias, note_text, warning) VALUES ('$_POST[hidden]', '$user', '$player->name', '$player->aliases', '$note','$_POST[warn]')";
$UpdateN2 = "INSERT INTO players WHERE `playerid` = $_POST[hidden] (warning) VALUES ('$_POST[warn]')";
mysqli_query($dbcon, $UpdateN, $UpdateN2);
The new line I added which seems to have broken it is '$UpdateN2'.
I am not sure if the new line has broken the statement, since I am new to PHP and mysqli any pointers to forums or websites that I can learn and understand this in a more detailed way I would appreciate.
Edit: I have since moved from using mysqli to PDO, I strongly suggestion that anyone willing to start using MYSQL commands with PHP to have a look at this: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I started reading this and testing things out, I find this much more easier but also it looks a lot cleaner and understandable when reading it back after a few days have passed.
In keeping with the mysqli procedural style in the original, using prepared statements with bind placeholders, something like this:
$UpdateN = 'INSERT INTO notes (uid, staff_name, name, alias, note_text, warning)'
. ' VALUES ( ?, ? , ? , ? , ? , ? )';
$UpdateN2 = 'UPDATE players SET warning = ? WHERE playerid = ? ';
if( $sth = mysqli_prepare($dbcon,$UpdateN) ) {
mysqli_stmt_bind_param($sth,'ssssss'
,$_POST['hidden']
,$user
,$player->name
,$player->aliases
,$_POST['note']
,$_POST['warn']
);
if( mysqli_stmt_execute($sth) ) {
// statement execution successful
} else {
printf("Error: %s\n",mysqli_stmt_error($sth));
}
} else {
printf("Error: %s\n",mysqli_error($dbcon));
}
if( $sth2 = mysqli_prepare($dbcon,$UpdateN2) ) {
mysqli_stmt_bind_param($sth2,'ss'
,$_POST['warn']
,$_POST['hidden']
);
if( mysqli_stmt_execute($sth2) ) {
// statement execution successful
} else {
printf("Error: %s\n",mysqli_stmt_error($sth2));
}
} else {
printf("Error: %s\n",mysqli_error($dbcon));
}
If it was me, I'd just make two separate calls to mysqli_query, one for each of your separate queries. PHP has historically been very wary of permitting multiple queries in a single function call, because of possible sql injection vulnerabilities.
On a related note, you need to sanitize your input. $_POST should never, ever, ever appear directly in a mysql query string, because your post data might -actually be something like ')"; DROP TABLE users;'.
Finally, you're using a WHERE clause on an insert. That's probably breaking your query. You should take a couple of days and research how and why that's breaking your query, and how and why to write proper sql queries. Doing so will add value to your company, because your company is less likely to suffer a catastrophic data breach, and it will add value to you, because you'll be a better SQL coder.
Edit: and in the time it took me to write this, three different people made each of those points. LOL.

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
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);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

mysql update query returning query empty

I have this update statement:
mysql_query ("UPDATE loan SET loan_reff_id='$_POST[loan_reff_id]',
commit_date='$_POST[commit_date]',app_loan_type='Tertiary Loan',
app_ln_amnt='$_POST[app_ln_amnt]', institution_name='$_POST[institution_name]',
app_course='$_POST[app_course]',course_length='$_POST[course_length]',
course_cost='$_POST[course_cost]', app_trm_pymnt='$_POST[app_trm_pymnt]',
app_intrst_rate=3
WHERE app_file_id='$_POST[app_file_id]'");
However wen I run the query it says query empty, what do you think might be the problem
Im using mysql and php
This one is not empty.
You are getting such an error from some other query.
According this one, to make it sane at the very least,
foreach($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
$sql = "UPDATE loan SET loan_reff_id='$_POST[loan_reff_id]',
commit_date='$_POST[commit_date]',app_loan_type='Tertiary Loan',
app_ln_amnt='$_POST[app_ln_amnt]', institution_name='$_POST[institution_name]',
app_course='$_POST[app_course]',course_length='$_POST[course_length]',
course_cost='$_POST[course_cost]', app_trm_pymnt='$_POST[app_trm_pymnt]',
app_intrst_rate=3
WHERE app_file_id='$_POST[app_file_id]'";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
You should not use directly $_POST values in your queries, you risk SQL injections, try using PDO.
Regarding the empty query, you must have a problem with simple/double quotes and concatenation.
Finally, are you sure you do not violate any constraint in your table ? NOT NULL, etc...

Unknown Column in 'field list'

The following code is responsible for the MySQL error Error In Insert-->Unknown column 'expert manager' in 'field list'. If I remove the code below it will solve the MySQL error. Do you know what's wrong with this piece of code?
$l=0;
$source = 'expertmanager';
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', ".$this->cat.", ".$course_id.",'".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, ".$close.", ".$source.")") or die("Error In Insert-->".mysql_error());
}
Thanks!
What is wrong with this piece of code:
Too short variable names
Don't use variable names that are shorter than 3-5 chars. Every variable name should describe the value(s) you want to store inside.
//bad
$l=0;
//good
$executionOrder = 0;
Concatenation of queries
Don't concatenate queries, it's a bad practice that leads to errors, insecure applications, etc. Don't use the mysql API either, it's outdated, insecure and will be deprecated. Use PDO and prepared statements instead.
//bad
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
//good
$statement = $db->prepare("DELETE FROM `student_questions` WHERE user_id = ?);
$statement->execute(array($userId));
Usage of die()
I see it all the time, and I see people telling other people to do that all the time. It's plain simply bad practice and it's time that people start to understand this. You cannot catch the error in any way. You cannot log the error. You cannot control whether it should be output to the screen or not. It's okay to do that in a development environment, but certainly not in a production environment.
You're vulnerable to SQL injection attacks
NEVER, NEVER include user data (session, get, post, cookie, etc.) unfiltered/unescaped into your queries.
//really bad
$query = "SELECT something FROM table WHERE " . $_POST['someValue'];
//better
$query = "SELECT something FROM table WHERE " . mysql_real_escape_string($_POST['someValue']);
//even better: use prepared statements as shown above
And finally the smallest thing that's wrong and the one that created your error
//bad
$query = "INSERT INTO `student_questions` (source) VALUES (expertmanager)"; //that's what you have
//better
$query = "INSERT INTO `student_questions` (source) VALUES ('expertmanager')";
Do you have a column called expert manager? If so, try changing the name to 'expert_manager' (without quotes), and see if that works.
You forgot quotes around several values in your insert statement :
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', '".$this->cat."', '".$course_id."','".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, '".$close."', '".$source."')") or die("Error In Insert-->".mysql_error());
}
Not only $source, there are also : $course_id, $close, etc.
You have not enclosed the value of $source (which is the string expert_manager) in single quotes in your query.
mysql_query("INSERT INTO `student_questions` (...snip...) VALUES (...snip...'".$school."', 1, ".$close.", '".$source."')") or die("Error In Insert-->".mysql_error());
//------------------------------------------------------------------------------------------------------^^^^^^^^^^^^^^^^
We cannot see the value of $close, but if it is a string value rather than numeric, it should probably be enclosed in quotes as well.
Additional note: I see $_POST['checkbox'][$i] passed directly into the query. Please make sure this input has been properly validated and escaped with mysql_real_escape_string() if necessary. The same rule may apply to other variables used in the VALUES() list, but we cannot see their origins with the code posted.

unable to insert into mysql database using php

$db = mysql_connect("localhost","root","123");
mysql_select_db("website_categorization") or die("\n error selecting database" );
$keyword_array = preg_split('/[\s,]+/', $tag);
foreach($keyword_array as $tag1)
{
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,$tag1)");
}
echo "\nAffected rows are ".mysql_affected_rows()."\n";
mysql_close($db);
Can u tell me what is the problem with this code??...I intend to insert rows into the category_keyword table from an array $keyword_array. I get errors "Affected rows are -1" and insertion does not work
You should quote and escape string values.
You should also handle errors, to be notified of them.
You should also write distinct statements, to be able to read your code later (as well as let others to read it).
$tag1 = mysql_real_escape_string($tag1);
$sql = "INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
insert multiple rows via a php array into mysql
You need to encapsulte the string $tag in a query, otherwise mysql will think its a column name
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'".mysql_real_escape_string($tag1)."')");
You should quote and escape your string columns
$tag1 =
mysql_real_escape_string($tag1);
mysql_query("INSERT INTO
category_keyword(ID_Category, Keyword)
VALUES(2,'$tag1')");
You should also handle the mysql query errors to know why the query get failed. With the current code you never know why it is failing.It is better to handle mysql errors.
mysql_query('Your query') or trigger_error(mysql_error());
You can use this:
mysql_query("INSERT INTO category_keyword SET ID_Category=2, Keyword=".$tag1.");
Better syntax to understand :)

Categories