How does the if statement in PHP work? - php

The code below does exactly what it's expected to do. It adds a client into the database successfully. But I never told the query to execute or add a new client all I did was store the query in a variable and checked to see if it was valid in the if statement. I need some help understanding how the query executed.
$query = "INSERT INTO clients(id, name, email, phone, address, company, notes, date_added) VALUES(NULL, '$clientName', '$clientEmail', '$clientPhone', '$clientAddress', '$clientCompany', '$clientNotes', CURRENT_TIMESTAMP)";
$result = mysqli_query($connection, $query);
// if query was successful
if( $result ){
header("LOCATION: clients.php?update=success");
} else{
// something went wrong
echo "Error: $query <br>" . mysqli_error($connection);
}

The way you should be doing this is a little more self-explanatory:
// Prepare this query with placeholders for where the user data will go.
// This creates a prepared statement handle ($stmt)
$stmt = $connection->prepare("INSERT INTO clients(name, email, phone, address, company, notes, date_added)
VALUES(?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)");
// Bind the user data to the statement so it will be escaped properly
// and inserted correctly.
$stmt->bind_param(
"ssssss",
$clientName,
$clientEmail,
$clientPhone,
$clientAddress,
$clientCompany,
$clientNotes
);
// Execute the statement now that everthing is in place. This actually
// sends the query to the MySQL server to be executed and waits
// for the result. The result of this function call indicates success
// or failure.
if ($stmt->execute()) {
// Query was successful then `execute()` returns a logically true value
// and this block of code will run.
header("Location: clients.php?update=success");
} else {
// If that previous condition didn't trigger, then we end up here and
// this code will run instead.
echo "Error: $query <br>" . $connection->error;
}
If you have an AUTO_INCREMENT column don't specify it in your list of VALUES, you can omit it and it will be populated automatically. Any column with a NULL default can also be omitted. There's no point in force-inserting NULL if that's how it will end up anyway.
You also need to pay careful attention to how you insert your data. You cannot use string interpolation to do this, it's extremely dangerous. The bind_param method takes care of adding the data in a safe manner if you've created a prepared statement that has placeholder values (?). This all but guarantees your code will be safe, secure and free from escaping errors that can take a lot of time to identify and repair.
I've also switched this to use the object-oriented style of mysqli. Not only is this significantly less verbose, it also becomes more clear as to what the operation is being performed on. $stmt->function() is obviously something making use of or manipulating the $stmt object. If it's just one argument of many that can be harder to identify.
Specifying arguments directly to functions instead of leaning on these intermediate variables is also a good habit to get into. Things like $sql tend to clutter up your code and confuse the intent of that string, plus if you have several of them you're juggling, like $sql3 and $sql8 there's an opportunity to make a tiny typo that causes real problems.

Related

How to test is row exists in the database

I have a table called user_bio. I have manually entered one row for username conor:
id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.
A bio is unique to a user, and obviously, a user cannot manually set their bio from inserting it in the database. Consider the following scenario's:
Logged in as Conor. Since Conor already has a row in the database, I simply want to run an UPDATE query to update the field where username is equal to conor.
Logged in as Alice. Since Alice has no row in the database corresponding to her username. Then I want to run an INSERT query. For all users, all users will have to have their details inputted, and then updated correspondingly.
At the moment, I am struggling with inserting data in the database when no rows exist in the database.
Here is my current approach:
$about_me = htmlentities(trim(strip_tags(#$_POST['biotextarea'])));
$new_studying = htmlentities(trim(strip_tags(#$_POST['studying'])));
$new_lang = htmlentities(trim(strip_tags(#$_POST['lang'])));
$new_rel = htmlentities(strip_tags(#$_POST['rel']));
if(isset($_POST['update_data'])){
// need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
$get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
$row_returned = mysqli_num_rows($get_bio);
$get_row = mysqli_fetch_assoc ($get_bio);
$u_name = $get_row['username'];
if ($u_name == $username){
$update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang',
relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
echo " <div class='details_updated'>
<p> Details updated successfully! </p>
</div>";
} else {
$insert_query = mysqli_query ($connect, "INSERT INTO user_bio
VALUES ('', '$age','$new_studying','$new_lang','$new_rel', '$username', '$about_me'");
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo " <div class='details_updated'>
<p> Details added successfully! $row_returned </p>
</div>";
}
}
The UPDATE query works fine, when logged in as Conor. But again, INSERT does not work when logged in as Alice.
MySQL support INSERT ... ON DUPLICATE KEY UPDATE type of queries. So you do not need to make few queries to check existance of row in your php code, just add corrct indexes and let your DB take care about this.
You can read about such type of queries here
Here are a few things you could do to make it work:
Prevent SQL injection
As this is an important issue, and the suggested corrections provided below depend on this point, I mention it as the first issue to fix:
You should use prepared statements instead of injecting user-provided data directly in SQL, as this makes your application vulnerable for SQL injection. Any dynamic arguments can be passed to the SQL engine aside from the SQL string, so that there is no injection happening.
Reduce the number of queries
You do not need to first query whether the user has already a bio record. You can perform the update immediately and then count the records that have been updated. If none, you can then issue the insert statement.
With the INSERT ... ON DUPLICATE KEY UPDATE Syntax, you could further reduce the remaining two queries to one. It would look like this (prepared):
INSERT INTO user_bio(age, studying, language,
relationship_status, username, about_me)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY
UPDATE studying = VALUES(studying),
language = VALUES(language),
relationship_status = VALUES(relationship_status),
about_me = VALUES(about_me);
This works only if you have a unique key constraint on username (which you should have).
With this statement you'll benefit from having the data modification executed in one transaction.
Also take note of some considerations listed in the above mentioned documentation.
NB: As in comments you indicated that you prefer not to go with the ON DUPLICATE KEY UPDATE syntax, I will not use it in the suggested code below, but use the 2-query option. Still, I would suggest you give the ON DUPLICATE KEY UPDATE construct a go. The benefits are non-negligible.
Specify the columns you insert
Your INSERT statement might have failed because of:
the (empty) string value you provided for what might be an AUTO_INCREMENT key, in which case you get an error like:
Incorrect integer value: '' for column 'id'
a missing column value, i.e. when there are more columns in the table than that you provided values for.
It is anyway better to specify explicitly the list of columns in an INSERT statement, and to not include the auto incremented column, like this:
INSERT INTO user_bio(age, studying, language,
relationship_status, username, about_me)
VALUES (?, ?, ?, ?, ?, ?)
Make sure you get notified about errors
You might also have missed the above (or other) error, as you set your error reporting options only after having executed your queries. So execute that line before doing any query:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
And also add there:
error_reporting(E_ALL);
ini_set('display_errors', 1);
In a production environment you should probably pay some more attention to solid error reporting, as you don't want to reveal technical information in the client in such an environment. But during development you should make sure that (unexpected) errors do not go unnoticed.
Do not store HTML entities in the database
It would be better not to store HTML entities in your database. They are specific to HTML, which your database should be independent of.
Instead, insert these entities (if needed) upon retrieval of the data.
In the below code, I removed the calls to htmlentities, but you should then add them in code where you SELECT and display these values.
Separate view from model
This is a topic on its own, but you should avoid echo statements that are inter-weaved with your database access code. Putting status in variables instead of displaying them on the spot might be a first step in the right direction.
Suggested code
Here is some (untested) code which implements most of the above mentioned issues.
// Calls to htmlentities removed:
$about_me = trim(strip_tags(#$_POST['biotextarea']));
$new_studying = trim(strip_tags(#$_POST['studying']));
$new_lang = trim(strip_tags(#$_POST['lang']));
$new_rel = trim(strip_tags(#$_POST['rel']));
// Set the error reporting options at the start
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['update_data'])) {
// Do not query for existence, but make the update immediately
$update_stmt = mysqli_prepare ($connect,
"UPDATE user_bio
SET studying = ?,
language = ?,
relationship_status = ?,
about_me = ?
WHERE username = ?");
mysqli_stmt_bind_param($update_stmt, "sssss",
$new_studying, $new_lang, $new_rel, $about_me, $username);
mysqli_stmt_execute($update_stmt);
$num_updated_rows = mysqli_stmt_affected_rows($update_stmt);
mysqli_stmt_close($update_stmt);
if ($num_updated_rows === 0) {
$insert_stmt = mysqli_prepare ($connect,
"INSERT INTO user_bio(age, studying, language,
relationship_status, username, about_me)
VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($insert_stmt, "isssss",
$age, $new_studying, $new_lang, $new_rel, $username, $about_me);
mysqli_stmt_execute($insert_stmt);
mysqli_stmt_close($insert_stmt);
}
// Separate section for output
$result = $num_updated_rows ? "Details updated successfully!"
: "Details added successfully!";
echo " <div class='details_updated'><p>$result</p></div>";
}
Aside from security issues and bad coding practices, here are a couple things you can do.
You don't need to compare the name to check if the bio already exists. You can just count the number of rows returned. If it is more than zero, then the user bio already exists.
When comparing strings, === is preferred over ==. You can read about it and find out why but here is an example (2nd answer)
You should really look into either REPLACE INTO or ON DUPLICATE KEY UPDATE. Just using either of there 2, depending on your use case pick one, you can pretty much eliminate more than half of your currently displayed code. Basically, both will insert and if the record already exists, they updates. Thus, you wouldn't even need to check if the record already exists.

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.

How can I test if PDO successfully binded my variables?

//The variables are declared outside this function. I use $_POST to retrieve each user input in another .php file using html form tag. The variable $db is my database connection.
function insertintodb ($db, $avar, $bvar, $cvar)
{
/*
How can I tell what values my variables are when using PDO bindParam? I output $avar to see its value in this function. How can I tell if PDO actually binded ":firstname" to $avar? Likewise with the other variables.
*/
echo 'before <br>';
echo $avar;
echo '<br>';
//firstname, midinitial, lastname are values in my database.
//name is my table I am inserting into.
$insertname = "INSERT INTO name (firstname, midinitial, lastname)
VALUES (:firstname, :midname, :lastname)";
echo 'before PDO prepare<br>';
echo $avar;
echo '<br>';
$stmt = $db->prepare($insertname);
$stmt->bindParam(':firstname', $avar);
$stmt->bindParam(':midname', $bvar);
$stmt->bindParam(':lastname', $cvar);
echo 'after binding variables using bindParam <br>';
echo $avar;
echo '<br>';
$stmt->execute();
echo 'after executing <br>';
echo $avar;
echo '<br>';
}
bindParam() returns true or false:
if($stmt->bindParam(':firstname', $avar)) {
echo 'Woo hoo yay!';
} else {
echo 'Boo hoo waa';
}
Just avoid bindParam at all. this will relieve you from burden of checking its result
function insertintodb ($db, $avar, $bvar, $cvar)
$sql = "INSERT INTO name (firstname, midinitial, lastname) VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$data = array_slice(func_get_args()); // lets strip $db from the func args
$stmt->execute($data);
}
Trust PDO
If PDO has a bug, this is not your problem. It is PDO's - since it's fairly well tested, there are very few bugs in current PDO versions. That is, if you tell PDO to bind, then trust that it will bind (PDO will fail on execute if there are unbound parameters, so we don't even have to "trust" it too much).
However, use PDOStatement::bindValue (not bindParam, except in special cases) because bindValue will ensure the value supplied is bound and not merely a "reference [to the variable]". This prevents "accidental changes" to variables between binding and execution from affecting the query.
Write and Test a DAL
Write a Data-Access Layer (DAL)1, as opposed to inline spaghetti SQL, and then test it. While ensuring the parameter is "actually binded" sounds useful, it isn't doesn't ensure the code is valid semantically. For instance, what if the code incorrectly did $stmt->bindParam(':firstname', $lastname);?
Furthermore, PDO itself will fail (I recommend enabling Exceptions) on most basic "binding failures" (such as unbound parameters or nonconvertible values) when the query is executed, making the very nature of testing if a parameter is "actually binded" less important.
Since detecting binding is not relevant to determining the validity of the code, nor can PDO report exactly what data is stored due SQL conversion issues (including truncation), then the problem really isn't about checking each bind, it's about checking operations - and a DAL provides guaranteed contracts for different operations.
1 A DAL doesn't have to be scary, nor does it have to use "ORM" or "OOP" or "DI/IOC" or anything else (although an advanced DAL may use all of those "concepts"). Consider, for starters, a small handful of functions in a separately included file which are the only mechanism for connecting to the database and "talking to" SQL.
Each of these functions then has a simple contract (which as documentation on the top) which defines the parameters it takes, the results it returns, and any exceptions it may throw.
Congratulations, you've created a minimal and testable DAL!
Then this DAL, which is just a collection of functions for now, can be taken and tested/verified outside of the "actual program" (preferably using an existing test framework/harness).

Error: Query was empty

$nam=$_POST['name'];
$fname=$_POST['family'];
$dat=$_POST['date'];
$bal=$_POST['balance'];
$curr=$_POST['currency'];
$con=mysql_connect('localhost', 'xxxx', 'xxxx', 'xxxx');
$db=mysql_select_db('users',$con);
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance, Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
die('Error: ' . mysql_error($con));
}
So guys, I got this code and I am trying to do something like a registration form. I have tripple checked the names of the variables and the query itself is working when executed in SQL database. The thing is when I include it in my php script it returns that the Query was empty. I've looked around but all errors on the Web are around not assigning to a variable or having several insert statements and so on. So my question is why am i getting this when I am actually inputting data from a web form? Error: Query was empty
P.S.
Ok so what I mde of this: I removed the check that you said was for a second time that is the if (!mysql_query($ins,$con)) { die('Error: ' . mysql_error($con)); } part now i get execution but it does not really add the entry to the database and i cannot call it. That is the new name.
You're basically trying to use mysql_query() twice:
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance,
Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
$ins will contain a valid MySQL resource if the query was executed correctly, but you're attempting to use it again in the if condition.
Just remove the mysql_query() part from the condition, like so:
if(!$ins) {
# code ...
}
That should fix this particular issue. But note that your code is vulernable to SQL injection. Also, mysql_* functions are deprecated and are soon to be removed. I recommend you switch to MySQLi or PDO and start using parameterized queries to be safe.
this is incorrect
if (!mysql_query($ins,$con))
why are you performing a query of a query ??
just use if (!$ins||!$con)) if you are trying to check if the query and connection has been successful

Can I use htmlentities() in an SQL query?

Much thanks for the discussion my original question generated. I took Jay's suggestion to use bind_param(), but there is something I don't understand about it that may be giving me the Server Error: "The website encountered an error while retrieving...". I don't know what the parameter 'sssd' that came with the example means.
Any suggestions as to what is generating the Server Error are much appreciated.
<?php
$mysqli = new mysqli('my-database-address', 'my-username', 'my-password', 'my-database-name');
f (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit(); }
$stmt = $mysqli->prepare("INSERT INTO volunteers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssd', $first_name, $last_name, $street_address, $apt_unit, $city, $zip,
$email, $phone, $planning, $signatures, $canvassing, $phone_bank, $media, $press_releases,
$volunteer_coordinator, $speaker, $house_parties, $web_page, $other, $skills, $organizations);
$first_name = '$_POST[first_name]'; $last_name = '$_POST[last_name]'; $street_address = '$_POST[street_address]';
$apt_unit = '$_POST[apt_unit]'; $city = '$_POST[city]'; $zip = '$_POST[zip]'; $email = '$_POST[email]';
$phone = '$_POST[phone]'; $planning = '$_POST[planning]'; $signatures = '$_POST[signatures]';
$canvassing = '$_POST[canvassing]'; $phone_bank = '$_POST[phone_bank]'; $media = '$_POST[media]';
$press_releases = '$_POST[press_releases]'; $volunteer_coordinator = '$_POST[volunteer_coordinator]';
$speaker = '$_POST[speaker]'; $house_parties = '$_POST[house_parties]'; $web_page = '$_POST[web_page]';
$other = '$_POST[other]'; $skills = '$_POST[skills]'; $organizations = '$_POST[organizations]';
$stmt->execute();
$stmt->close();
echo "<br /><br />";
echo "<div class='center-col-wrap'>";
echo "Your information has been received.";
echo "<br /><br />";
echo "Thank you for volunteering!"; echo "<br />";
echo "Your help in this effort to bring greater democracy to Oakland"; echo "<br />";
echo "will go a long way to create a healthy and informed community."; echo "<br />";
echo "<br /><br />";
echo "<a href='http://communitydemocracyproject.org/'>Return to CDP Home Page.</a>";
echo "</div>";
$mysqli->close();
?>
MY ORIGINAL QUESTION IS BELOW:
I didn't know if this would work or not. It does not So how can I use htmlentities() here?
Any help is much appreciated.
$sql="INSERT INTO volunteers (first_name, last_name, street_address, apt_unit, city, zip, email, phone,
planning, signatures, canvassing, phone_bank, media, press_releases, volunteer_coordinator, speaker,
house_parties, web_page, other, skills, organizations)
VALUES
('htmlentities($_POST[first_name])','htmlentities($_POST[last_name])','htmlentities($_POST[street_address])',
'htmlentities($_POST[apt_unit])','htmlentities($_POST[city])','htmlentities($_POST[zip])',
'htmlentities($_POST[email])','htmlentities($_POST[phone])','$_POST[planning]','$_POST[signatures]','$_POST[canvassing]','$_POST[phone_bank]',
'$_POST[media]','$_POST[press_releases]','$_POST[volunteer_coordinator]','$_POST[speaker]',
'$_POST[house_parties]','$_POST[web_page]','$_POST[other]','htmlentities($_POST[skills])','htmlentities($_POST[organizations])')";
You never want to use htmlentities() on data that's going to be inserted into the database!
NEVER!
Only use it when you are outputting data to a web page.
Otherwise, if you ever want to do anything with that data, ever, that's not directly to a web browser (think, sending emails, or counting words, or outputting to CSV, what have you), you'll quickly realize your error.
As Theodore said, never use htmlentities() for "escaping" something you want to put in your DB.
I strongly recommend to use prepared statements when anything that (could) come from outside (the user) is stored in a database.
Prepared statements are really easy to use.
If you use PDO to access you database help can be found here.
As you can see the bindParam() method is used to assign any value to a placeholder in the query.
If you use mysqli you can find the docs here.
The syntax of bind_param() is slightly different since the placeholders don't have names (order matters) and first argument is a string that determines what type the arguments have ("s" for string, "i" for integer and so on).
Using prepared statements has several positive effects. First of all it automatically masks the data that is provided in the bindParam()/bind_param() method and is the best way to close the SQL injection attack vector and it even optimizes the performance of your queries by storing the execution plan in the database (this has a little overhead but if you execute a query twice it pays off double).
PS: htmlentities() should only be used if you want to display some HTML as raw text to your users (code listings for instance).
PPS: Don't use real_escape_string() to prevent SQL injection since it's not safe (supeskt.org)
Update
First of all, for a follow up you should ask a new question. People don't read questions that are already marked as answered and by opening new questions you give kind people an opportunity to get some reward. :)
Nevertheless, the first argument "sssd" tells the database provider that you are passing four arguments, three of type string and a fourth of type double (in the example in the docs three strings and one double are bound ("DEU", "Bavarian", "F" and 11.2)). This is obviously not the case here, you are actually passing (binding) 21 values.
Depending of the type that the columns in your volunteers table have you need to pass a string of 21 characters as the first argument.
There are four possible chars that can be used to determine the type:
i for integer
d for double (floating point numbers)
s for string
b for boolean
All you have to do is to check what types you DB columns have. You will see that the types in the database have different names (like varchar, float etc.). If you google for this names you will find out that they are similar to string, integer, double and boolean. So you have to choose the best matching type depending on the column type (string ≆ varchar, double ≆ float, string ≆ tinytext, string ≆ date/datetime etc. pp.) and you should ensure that the values (your $_POST variables) actually match the type you defined.
Assuming that all your columns are of an text like type like varchar, the first argument would look like 'sssssssssssssssssssss' (21 times s) or 'ssssssssssssssissssss' if the column that takes the volunteer_cordinator is of type int (just for instance).
After you have done this you should double check if f (mysqli_connect_errno()) is a copy&paste related mistake or if you have actually missed the i in your code (should be if (mysqli_connect_errno())).
If you have checked that you should consider to write $_POST['xyz'] instead of '$_POST[xyz]', it will help you, really (' marks the start/end of a string and xyz is in fact the string here).
If you still encounter errors enable more detailed error information by adding error_reporting(E_ALL); at the top of your file (you should remove this for security reasons when your site goes live) and ask a new question.
Update 2
Double check your MySQL connection string (the arguments you pass in the mysql() method). Are you sure that your password starts with an # and ends with a full stop? By the way, you shouldn't post passwords etc. in the public.
Ensure that you server supports the mysqli methods by running a script containing only
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>
and check the output for something like this:
To answer your question exactly as you wanted, you'll need to exit out of your string:
$sql="INSERT INTO volunteers (...) VALUES
('".htmlentities($_POST['first_name'])."','".htmlentities($_POST['last_name'])'." ...
(But please, as Theodore clearly says, don't do this. It's bad. Really, don't do it. Please!)
I think you're trying to escape your input/output. The best way to do is is firstly to stop SQL injection, use your favourite DB escaping method. I'm just using this as an example, you might have a better setup than this short example code:
$sql="INSERT INTO volunteers (...) VALUES
('".$mysqli->real_escape_string($_POST['first_name'])."','".$mysqli->real_escape_string($_POST['last_name'])'." ...
And then when you output, escape using htmlentities:
echo htmlentities($output->first_name);

Categories