PHP Functions in a SQL insert

I’m working on a little form for a non-profit to help them manage some of their information. The form is mostly made up of checkboxes which need to enter “true” into their database column if they are checked or, if they’re not checked enter “false” into their database column. I’m trying to write a little function that I can use to make this distinction for each column I’m entering a variable into. Is there a way for me to use a function inline in SQL to do this? What I’m trying now is this:



function checkValue($value) {
	if(!$value) {
		$value = 'false';
	}
	$value;
}

mysql_select_db("codejunkie_clients", $con);
mysql_query("INSERT INTO boulderreads_tutor_reports 
(got_job, got_better_job, improved_on_the_job_skills)
VALUES (" . checkValue($_POST['got_job']) . ", 'true', 'true')");

mysql_close($con);

You’ll need to return or echo the $value in your function, at the moment it’s not actually doing anything once it reaches the end of the function.

That worked! Thank you for the help. Unfortunately, now the SQL insert is turning “true” into a 1 and “false” into a 0 when they’re inserted into the database as values. For this project, my client needs them to say “true” or “false”. Is there a way to keep sql from turning them into numbers?

What data type is the column got_job?

It’s tinytext.

The query is going to look like this:

INSERT INTO boulderreads_tutor_reports 
(got_job, got_better_job, improved_on_the_job_skills)
VALUES (true, 'true', 'true')

With no quotes around the first true, so it won’t be treated as a string. Try building your query in a string so you can echo it to debug if you have troubles in future.

Also if some other string like ‘catapult’ is passed into checkValue then that will be returned instead of ‘true’

This might be better


function checkValue($value) {
  if(strtolower($value) === 'true') {
    return 'true';
  }
  return 'false';
}

I think you should escape the string and add doube/single quotes around it.
The function ‘addslashes’ will do the job.

I forgot to mention that CHAR(4) would be a better data type for true/false as a string.

Or more compact still would be TINYINT UNSIGNED and your code would translate 1 to true and 0 to false for display.