PHP not inserting some values into MySQL database - php

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [blank]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.

Well it will insert the final value only , because you are executing the $sql and the last values of $sql is "INSERT INTO scores (result) VALUES ('$_POST[result]')"; You are overiding the previous values by putting same variable name.
Also (!empty($_POST[hometeam])) remove the !empty if the fields can be blank sometimes.

You are overwriting your SQL statements each time. Beacue your 'result' field isn't blank, you are setting your SQL statement to:
"INSERT INTO scores (result) VALUES ('$_POST[result]')"
This is the only statement which is then being executed - your other values are being ignored as they are not part of this statement.
What you need to do is set up your variables first:
$hometeam = isset($_POST['hometeam']) ? $_POST['hometeam'] : NULL;
$awayteam = isset($_POST['awayteam']) ? $_POST['awayteam'] : NULL;
$result = isset($_POST['result']) ? $_POST['result'] : NULL;
You can then do your database interaction:
$sql = "INSERT INTO scores hometeam, awayteam, result VALUES $hometeam, $awayteam, $result";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
I should say that I haven't included any security on this - you should look into PDO or prepared statements to make sure your database isn't open to SQL Injection.
Hope this helps!

First off, there's a huge security flaw in this code, which is not sanitizing your inputs. A user could insert whatever they like and it's executed on the DB without any checking. This is bad.
At the very least, you should be using something like mysql_real_escape_string(), even though even that is not exactly the best thing for the job (Google PHP + PDO for example).
Secondly, you're actually executing one query using one variable. If $_POST['result'] is set, then $sql will always be the last value. What you might want to do is make the query like so:
$query = 'INSERT INTO scores ('.$fields.') VALUES ('.$values.')';
And construct the $fields and $values variables using your if(!empty( .. )) code.
But to reiterate SANITIZE YOUR INPUTS

3 insert into statements will insert 3 records, with unspecified fields left as null or default.
you must use 1 insert into statement, something like:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
#$sql="INSERT INTO scores (hometeam,awayteam,result) VALUES ('{$_POST[hometeam]}','{$_POST[awayteam]}','{$_POST[result]}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
here, unspecified values will come as empty string, if that is a problem, first assign them to 3 seperate variables with ifs (e.g. set empty ones to null), then use them

I think there is some problem with the declaration of name of your input field in you html form. Make sure, $_POST[hometeam] must be the same input name in your form
Example:
In your form
<input type="text" name="hometeam" value="" />
In your PHP
if (!empty($_POST[hometeam])) {
$sql="INSERT INTO scores (hometeam) VALUES ('$_POST[hometeam]')";
}
And also, please use addslashes or mysql_real_escape_string in your post values before adding it on the database.
Look at this link below:
http://php.net/manual/en/function.addslashes.php
http://php.net/manual/en/function.mysql-real-escape-string.php

if (!empty($_POST['hometeam'])) {
$sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
}
Notice the single quotes around the 'hometeam' part.
You should also clean that using mysql_real_escape_string($_POST['hometeam']).
Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).

Related

Insert data from 1 form into 2 Mysql DBs

I am trying to use one form to insert data into 2 tables.
I have one table, Members and another, Members.
Here is my code:
<?php
$first_name=$_POST[first_name];
$last_name=$_POST[last_name];
$email_address=$_POST[email_address];
$staff=$_POST[staff];
$type=$_POST[type];
$descr=$_POST[descr];
$time=$_POST[time];
mysql_select_db("cl49-vogclients", $con); $sql="INSERT INTO member
(first_name,last_name,email_address)
VALUES
('$first_name','$last_name','$email_address')";
if (!mysql_query($sql,$con)) { die('Error adding client ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Client Added Succesfuly</font> </h2>';
$sql1="INSERT INTO audit
(staff,type,descr)
VALUES
('$staff','$type','$descr')";
if (!mysql_query($sql1,$con)) { die('Audit Unsucsessful ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Audit Succesful</font> </h2>';
This adds the client/member but not add anything to the audit database?
This is because you are only executing the first query:
mysql_query($sql,$con)
You have to call it seperatly for $sql1
Besides that: Please bear in mind that mysql like this is heavily outdated and deprecated. You should really look into PDO and prepared statements.
http://php.net/manual/de/book.pdo.php
You have closeds SQL
You need to remove mysql_close($con);

MySQL error on form submission

I'm getting a mysql error saying "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..."
Here's the basics of my code:
First I'm populating the select menu options with rows from the categories table. This is working fine:
<select id="dropdown-select" name="Name">
<option value="" id="dropdown-option">Please select a category.</option>
<?php
$query_categories = "SELECT * FROM categories";
$result_categories = mysql_query($query_categories) or die(mysql_error());
while($categories_row = mysql_fetch_array($result_categories)) {
echo '<option id="dropdown-option" value="' . $categories_row['cat_name'] . '">' . $categories_row['cat_name'] . '</option>';
}
?>
</select>
Later, when I go submit the form to the transactions table (the above table I pulled data from was the categories table, could this be a problem?) is when I get the error. I think its related to the above code bc if I remove this element from my form submission, it writes the rest of the values to the database without any errors.
if(!isset($_POST['Name'])) {
die('You must select an income or expense from the drop down menu.');
} else {
$Name = $_POST['Name'];
}
//create query
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
$result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
Thanks for any help you can provide.
You are missing a single quote in your insert statement before $Budgeted
INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', '$Budgeted', '$Actual')"
If you have some fields which are defined in Database as VARCHAR, CHAR.
Also, if you are inserting a string value in Database from a PHP script, you need to add an enclosing single quote (') around it.
In your case, you are inserting a string without semicolons, so, it showing error in MySQL.
Your statement should be corrected by adding a single quote around $budget as:
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month',
'$Name', '$Budgeted', '$Actual')";
------^
The error "You have an error in your SQL syntax" is exactly correct!
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual)
VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
Look here, you missed something ----^
There is a ' missing from your statement causing the syntax error. Put the single quote in and you should be good to go!

Can not send information from PHP form to multiple mysql database tables

I am trying to insert data into 4 tables ( asset, asset_details, invoice and location). When I submit the form, it tells me that all the data has been submitted successfully but when I check the MySQL database the information is only submitted to the location tables.
Any help will be appreciated, Thank you .
mysql_query("START TRANSITION");
$query1 =("INSERT INTO .asset (asset_tag, asset_number, cap_ex, asset_type_id, invoice_id, status)
Values(".$_POST['asset_tag'] .",,,".$_POST['asset_type'] . ",".$_POST['invoice_number']."," . $_POST['status_id'] .")");
$query2 =("INSERT INTO .asset_details (asset_type_id, asset_tag, asset_type, physical_asset_id, manufacturer, os, os_version, make, model, serial_number, processor, ram, memory, hdd, host_name, notes)
Values(" .",".$_POST['asset_tag']."," .$_POST['asset_type'].",,
,".$_POST['os'].",".$_POST['os_version'].",".$_POST['make'].",".$_POST['model'].",".$_POST['serial_number'].",".$_POST['processor'].",,".$_POST['memory'].",".$_POST['hdd'].",,".$_POST['notes'].")");
$query3 =( "INSERT INTO .invoice (invoice_number, invoice_date, purchas_price, quantity, order_date, vender, warrenty_end, notes)
Values(" .$_POST['invoice_number'].",". $_POST['invoice_date'].",". $_POST['purchase_price'].",,,". $_POST['vender'].")");
$query4 =( "INSERT INTO .location (location_name, rack, row, unit)
Values(" .$_POST['location_name'].",".$_POST['rack'].",".$_POST['row'].",".$_POST['unit'].")");
echo "$query1 $query2 $query3 $query4";
$result1= mysql_query($query1);
$result2= mysql_query($query2);
$result3= mysql_query($query3);
$result4= mysql_query($query4);
$result = mysql_query("COMMIT");
if (!$result)
{
mysql_query("ROLLBACK");
die('Invalid query: ' . mysql_error());
}
else
{
echo "<script>alert('SUCCESS!');</script>";
}
}
mysql_close($con);
?>
There are some strange things;
START TRANSITION should probably be START TRANSACTION.
You're not quoting any of your string values. Strings need to be quoted using ' a'la INSERT INTO TEST VALUES ('olle');
An empty field cannot be indicated by just skipping it, you're doing INSERT INTO TEST (a,b,c) VALUES (1,,2); which is not valid syntax for not setting b.
Also, I recommend using a more modern mysql api than mysql_query, as for example PDO or mysqli, since injecting POST values into a string as you do can be pretty dangerous, you may cause SQL injection problems.
Use '`'s around each attributes(columns) and ''' around each values, it should work
During development, I'd echo each query-expressions before it is sent to the database..
...by the way, mysql_error() is a useful function in php, which returns the last error information of mysql....U may use that for debugging

Anyone know why this MYSQL INSERT doesn't work?

$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("pilot", $con);
$sql = "INSERT INTO logs (id, userid, date, plane, from, to, blocksoff, takeoff,
landing, blockson, flighttime, traveltime, tachobefore, tachoafter, tacho,
hobbsbefore, hobbsafter, hobbs, landings) VALUES ('$nfid', '$nfuserid',
'$nfdate', '$nfplane', '$nffrom', '$nfto', '$nfblocksoff', '$nftakeoff',
'$nflanding', '$nfblockson', '$nfflighttime', '$nftraveltime', '$nftachobefore',
'$nftachoafter', '$nftacho', '$nfhobbsbefore', '$nfhobbsafter', '$nfhobbs',
'$nflandings')";
mysql_query($sql);
there ain't nothing wrong with the $sql, it seems like it just wont query.. :(
id|userid=int(11)
date=date
plane|from|to=text
blocksoff|takeoff|landing|blockson=time
flighttime|traveltime|tachobefore|tachoafter|tacho|hobbsbefore|hobbsafter|hobbs|landings=double
all of the $ variables come from a textbox (if it matters)
May be some of the column names are MySql reserved words (especially from and to). Please escape them.
INSERT INTO logs (`id`, userid, date, plane, `from`, `to` ...)
You should always be checking for errors:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Kind of an open ended question....
Are any of your variables returning NULL values? If you are trying to insert NULL into the database, and the database column isn't set to accept NULL values, that could be causing an error.
You need to see what the query is actually doing. If you have any single quotes or other invalid character from the textbox, that could be screwing you up.
Also, for your own personal improvement, look up PDO. It helps you write much more secure queries through the use of prepared statements.
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Creating an "update" page MYSQL/PHP

I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.

Categories