I have a database storing materials in their respective formats, i.e. The Idiot (novel), Hamlet (play), Star Wars (screenplay), etc.
I’m using a PHP function that removes articles (i.e. The/A/An/', etc.) and creates a variable ($mat_alph, assigned NULL if non-existent) by which it can later be alphabetised. This is only required for titles with articles, but for those without one, I want this saved in the database as a NULL value.
Saving the variable in a NULL state stores it as an empty string rather than an actual NULL value, which causes problems later when filtering results by IS NULL/IS NOT NULL (which I’ll need to do when using SELECT commands with CASE WHEN to call mat_nm for those without an article and mat_alph for those with). I don’t want to save a mat_alph value for titles without an article as this will apply to a huge amount, repeating the mat_nm value and wasting memory.
Is it possible to use CASE WHEN in an UPDATE statement using the PHP variable as the argument?
The below attempt handles titles without articles well enough (i.e. Hamlet updates mat_alph to NULL) but with articles (i.e. The Idiot) creates this error:-
Truncated incorrect DOUBLE value: ‘Idiot’
$sql= "UPDATE mat SET
mat_nm='$mat_nm',
mat_alph=CASE WHEN ('$mat_alph') THEN '$mat_alph' END,
mat_url='$mat_url',
frmtid=(SELECT frmt_id FROM frmt WHERE frmt_url='$frmt_url')
WHERE mat_id='$mat_id'";
Is this possible or do I need a separate SQL UPDATE command solely for updating the mat_alph field?
The problem also applies to the initial INSERT commands and I expect the solution will apply to both.
$sql = "INSERT INTO mat(mat_nm, mat_alph, mat_url, frmtid)
SELECT
'$mat_nm',
'$mat_alph',
'$mat_url',
frmt_id FROM frmt WHERE frmt_url='$frmt_url'";
Thanks in advance.