I am reading BYO Database Driven Website, and am a little confused on a concatenation issue. On Page 134, in the example on inserting data into the Database it shows the following
sql = ’ INSERT INTO joke SET
joketext =" ’ .$_POST [’ joketext ‘] .’ ",
jokedate =“todays date” ';
The question is on the joketext portion. What is the purpose of all the quotes (single, and double, along with two contatenators, one on each end of the $_POST [ ’ joketext ’ ] array )
Is all this necessary, can’t it just be put in as joketext=“$_POST [ ’ joketext ’ ]” ?
I am confused on if I should use this structure on all future insert commands, is this is a norm, and if so, could you explain the logic.
Thank you.
Allex
Yes, quotes can sure be confusing and cause some messy looking code.
The best thing to do is to find a way that makes sense to you and stick to it as much as possible. PHP parses anything inside double quotes, but doesn’t parse anything inside single quotes. Hence the frequent need to concatenate string - variable - string sequences. Add to this that parts of the MySQL query need quotes around them to meet syntax requirements. I agree, to look at it - ugh!
As for $result, the foreach is getting
$result[0][‘joketext’]
$result[1][‘joketext’]
$result[2][‘joketext’]
…
so they are not all the same. The foreach “steps out” of the multi-dimensional array so the inner code is dealing with straight arrays. If you wanted a specific row, instead of foreach you could use a for using something like
$result[$i][‘joketext’]
instead, or go after a row by it’s first array key
On page 127 of the book, it shows that when you want to work with a result set out of the database, that you can use the mysqli_fetch_array() function to return a result set. And once it returns a result set, that the result set is returned as an associative array, with the column name being the indice for that array. Ok, so once you put this into a while loop, does the while loop return all the rows with the same indice name for each row?
For example if the while loop returns $row[‘joketext’} for the element in the first row of the result set, on the second iteration through the loop would it send out the second associative array as $row[’ joketext '] also? And so on until the loop finishes? And if so, how could you access a particular element if they are all named the same?
Thanks for your time,
Allex