mysql update query returning query empty - php

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

Related

Seemingly identical sql queries in php, but one inserts an extra row

I generate the below query in two ways, but use the same function to insert into the database:
INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');
The below method results in CORRECT inserts, with no extra blank row in the sql database
foreach($_POST as $item)
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.
$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";
Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.
I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.
below is my insert function for reference:
function do_insertion($query) {
$db = get_db_connection();
if(!($result = mysqli_query($db, $query))) {
#die('SQL ERROR: '. mysqli_error($db));
write_error_page(mysqli_error($db));
} #end if
}
Thank you for any insite/help on this.
Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.
The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?
!~ Pseudo Code DO NOT USE IN PRODUCTION ~!
foreach($_POST as $item)
{
if(isset($item) && $item != "")
{
$statement .= "'$item', ";
$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";
}
}
Please read #tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.
as #yycdev stated, you are in risk of SQL injection. Start by reading this and rewrite your code by proper use of protecting your database. SQL injection is not fun and will produce many bugs.

my mysql table doesnt get refreshed what to do

after inseet/delete /update i have to manually update the page until i see the result..why? how can i solve this problem
if (isset($_POST['action']) && $_POST['action']=='submitted') {
if (isset($_POST['update'])) {
$selected = $_POST['selected'];
for ($i=0; $i<$columncount;$i++){
$value[$i] = $_POST[$name[$i]];
foreach ($selected as $j)
mysql_query ("UPDATE $tablename set $name[$i]='".$value[$i][$j]." 'WHERE $name[0]=".$value[0][$j]);}
}
its reading table value from a form and updating
Because you update the database after displaying the table.
In other words, you fetch the values, display them, then update them. To fix this just put the above code above the table display.
Other than the obvious SQL injection vulnerabilities that are just begging to get your server pwn3d, you have no error handling whatsoever on your query - you're assuming it succeeded. Why not take the extra 2 seconds to try and handle the possibility that your query might actually have a syntax error?
$result = mysql_query(...) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
Try this one. Hope it will work
mysql_query ("UPDATE ".$tablename." set ".$name[$i]."='".$value[$i][$j]."' WHERE ".$name[0]."='".$value[0][$j]."';");}

ON DUPLICATE KEY UPDATE creating new records

I am having problems with the following code, it seems to work and creates the records just fine, the problem is each time I hit submit, instead of it updating the record it just creates a new one. If I turn off auto incremental for the primary key it updates the record just fine but then doesn't create any new ones, it seems either one or the other :-S
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('$_POST[cf_id]','$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
did you already try to echo your query string? guess the variable replacement inside it is wrong. try something like that for debugging:
<?php
$sql = "INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('{$_POST['cf_id']}','{$_POST['cf_uid']}','{$_POST['emailformname']}','{$_POST['datesent']}')
ON DUPLICATE KEY UPDATE
datesent='{$_POST['datesent']}'";
echo $sql; // for debugging
$query = mysql_query($sql) or die(mysql_error());
?>
Note the corrected variable names above. (curly braces around it, quotes around the array index)
I can't imagine it's the problem, but does the same thing happen when you cast the ID to an int and leave out the quotes?
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
(" . (int) $_POST['cf_id'] . ",'$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
By the way, you really shouldn't use your $_POST variables in your query without mysql_real_escape_string or better yet, use prepared statements (PDO or mysqli).

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

mysql query insert issue

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;

Categories