Foreach with different final loop









up vote
-2
down vote

favorite
1












I'm trying to create a foreach loop which changes the values of two variables. The last iteration of the loop is slightly different (removed comma at the end) - I can't seem to get it to work.



This is what I have so far



$rego_columns = [
"make",
"model",
"year",
"rego",
];

foreach ($rego_columns as $key => $regcolex)
if ($key === key($rego_columns))
$table_values = "'".$record["$regcolex"]."'";
$table_columns = "`.$regcolex.`";
else
$table_values = "'".$record["$regcolex"]."',";
$table_columns = "`.$regcolex.`,";











share|improve this question



















  • 1




    consider using a for loop and use the index
    – Daniel A. White
    Nov 12 at 0:54






  • 3




    what results are you getting now as opposed to the desired results? Define "not working".
    – Funk Forty Niner
    Nov 12 at 1:02










  • $table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
    – Kashmir96
    Nov 12 at 1:05






  • 1




    Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
    – Phil
    Nov 12 at 1:06










  • If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
    – Funk Forty Niner
    Nov 12 at 1:11















up vote
-2
down vote

favorite
1












I'm trying to create a foreach loop which changes the values of two variables. The last iteration of the loop is slightly different (removed comma at the end) - I can't seem to get it to work.



This is what I have so far



$rego_columns = [
"make",
"model",
"year",
"rego",
];

foreach ($rego_columns as $key => $regcolex)
if ($key === key($rego_columns))
$table_values = "'".$record["$regcolex"]."'";
$table_columns = "`.$regcolex.`";
else
$table_values = "'".$record["$regcolex"]."',";
$table_columns = "`.$regcolex.`,";











share|improve this question



















  • 1




    consider using a for loop and use the index
    – Daniel A. White
    Nov 12 at 0:54






  • 3




    what results are you getting now as opposed to the desired results? Define "not working".
    – Funk Forty Niner
    Nov 12 at 1:02










  • $table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
    – Kashmir96
    Nov 12 at 1:05






  • 1




    Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
    – Phil
    Nov 12 at 1:06










  • If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
    – Funk Forty Niner
    Nov 12 at 1:11













up vote
-2
down vote

favorite
1









up vote
-2
down vote

favorite
1






1





I'm trying to create a foreach loop which changes the values of two variables. The last iteration of the loop is slightly different (removed comma at the end) - I can't seem to get it to work.



This is what I have so far



$rego_columns = [
"make",
"model",
"year",
"rego",
];

foreach ($rego_columns as $key => $regcolex)
if ($key === key($rego_columns))
$table_values = "'".$record["$regcolex"]."'";
$table_columns = "`.$regcolex.`";
else
$table_values = "'".$record["$regcolex"]."',";
$table_columns = "`.$regcolex.`,";











share|improve this question















I'm trying to create a foreach loop which changes the values of two variables. The last iteration of the loop is slightly different (removed comma at the end) - I can't seem to get it to work.



This is what I have so far



$rego_columns = [
"make",
"model",
"year",
"rego",
];

foreach ($rego_columns as $key => $regcolex)
if ($key === key($rego_columns))
$table_values = "'".$record["$regcolex"]."'";
$table_columns = "`.$regcolex.`";
else
$table_values = "'".$record["$regcolex"]."',";
$table_columns = "`.$regcolex.`,";








php arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 1:02









Funk Forty Niner

80.5k1247100




80.5k1247100










asked Nov 12 at 0:52









Kashmir96

83




83







  • 1




    consider using a for loop and use the index
    – Daniel A. White
    Nov 12 at 0:54






  • 3




    what results are you getting now as opposed to the desired results? Define "not working".
    – Funk Forty Niner
    Nov 12 at 1:02










  • $table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
    – Kashmir96
    Nov 12 at 1:05






  • 1




    Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
    – Phil
    Nov 12 at 1:06










  • If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
    – Funk Forty Niner
    Nov 12 at 1:11













  • 1




    consider using a for loop and use the index
    – Daniel A. White
    Nov 12 at 0:54






  • 3




    what results are you getting now as opposed to the desired results? Define "not working".
    – Funk Forty Niner
    Nov 12 at 1:02










  • $table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
    – Kashmir96
    Nov 12 at 1:05






  • 1




    Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
    – Phil
    Nov 12 at 1:06










  • If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
    – Funk Forty Niner
    Nov 12 at 1:11








1




1




consider using a for loop and use the index
– Daniel A. White
Nov 12 at 0:54




consider using a for loop and use the index
– Daniel A. White
Nov 12 at 0:54




3




3




what results are you getting now as opposed to the desired results? Define "not working".
– Funk Forty Niner
Nov 12 at 1:02




what results are you getting now as opposed to the desired results? Define "not working".
– Funk Forty Niner
Nov 12 at 1:02












$table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
– Kashmir96
Nov 12 at 1:05




$table_columns and $table_values are used in a mySQL insert query. Currently, there are no records being received by the insert
– Kashmir96
Nov 12 at 1:05




1




1




Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
– Phil
Nov 12 at 1:06




Those `.make.`, etc strings don't look right. Also, PDO's prepared statement binding would surely help here
– Phil
Nov 12 at 1:06












If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
– Funk Forty Niner
Nov 12 at 1:11





If this is a database related issue also as you stated in a comment above, then the proper tags and code should be made part of the question, IMHO (<edit).
– Funk Forty Niner
Nov 12 at 1:11













1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










As you are effectively trying to map $record to your $rego_columns, I suggest using array_map to retrieve the values.



Then you can use implode to add the wrapping quotes or backticks around the array values.



Example https://3v4l.org/h70pO



$rego_columns = [
"make",
"model",
"year",
"rego",
];

$record = ['make' => 'A', 'model' => 'B', 'year' => 'C', 'rego' => 'D'];

$tableValues = array_map(function($r) use ($record)
return $record[$r];
, $rego_columns);

$tableColumns = '`' . implode('`,`', $rego_columns) . '`';
$tableValues = '"' . implode('","', $tableValues) . '"';


echo 'INSERT INTO table_name (' . $tableColumns . ') VALUES (' . $tableValues . ')';


Results in



INSERT INTO table_name (`make`,`model`,`year`,`rego`) VALUES ("A","B","C","D");



If you needed the dots included around the table column values for some reason, change the implode to:



$tableColumns = '`.' . implode('.`,`.', $rego_columns) . '.`';
$tableValues = '"' . implode('","', $tableValues) . '"';


Results in: https://3v4l.org/1DI76



INSERT INTO table_name (`.make.`,`.model.`,`.year.`,`.rego.`) VALUES ("A","B","C","D")



As a side note, I strongly suggest using prepared statements whenever using variable data with a database. And adopting this to map the values to the placeholders.



Example https://3v4l.org/kcl4m



$tableValues = array_map(function($r) use ($record) 
return $record[$r];
, $rego_columns);
$placeholders = implode(',', array_fill(0, count($tableValues), '?'));
$tableColumns = '`' . implode('`,`', $rego_columns) . '`';

$query = 'INSERT INTO table_name (' . $tableColumns . ') VALUES(' . $placeholders . ')';

$stmt = $pdo->prepare($query);
$stmt->execute($tableValues);





share|improve this answer






















  • thank you very much for your help and advice
    – Kashmir96
    Nov 12 at 4:03










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254753%2fforeach-with-different-final-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










As you are effectively trying to map $record to your $rego_columns, I suggest using array_map to retrieve the values.



Then you can use implode to add the wrapping quotes or backticks around the array values.



Example https://3v4l.org/h70pO



$rego_columns = [
"make",
"model",
"year",
"rego",
];

$record = ['make' => 'A', 'model' => 'B', 'year' => 'C', 'rego' => 'D'];

$tableValues = array_map(function($r) use ($record)
return $record[$r];
, $rego_columns);

$tableColumns = '`' . implode('`,`', $rego_columns) . '`';
$tableValues = '"' . implode('","', $tableValues) . '"';


echo 'INSERT INTO table_name (' . $tableColumns . ') VALUES (' . $tableValues . ')';


Results in



INSERT INTO table_name (`make`,`model`,`year`,`rego`) VALUES ("A","B","C","D");



If you needed the dots included around the table column values for some reason, change the implode to:



$tableColumns = '`.' . implode('.`,`.', $rego_columns) . '.`';
$tableValues = '"' . implode('","', $tableValues) . '"';


Results in: https://3v4l.org/1DI76



INSERT INTO table_name (`.make.`,`.model.`,`.year.`,`.rego.`) VALUES ("A","B","C","D")



As a side note, I strongly suggest using prepared statements whenever using variable data with a database. And adopting this to map the values to the placeholders.



Example https://3v4l.org/kcl4m



$tableValues = array_map(function($r) use ($record) 
return $record[$r];
, $rego_columns);
$placeholders = implode(',', array_fill(0, count($tableValues), '?'));
$tableColumns = '`' . implode('`,`', $rego_columns) . '`';

$query = 'INSERT INTO table_name (' . $tableColumns . ') VALUES(' . $placeholders . ')';

$stmt = $pdo->prepare($query);
$stmt->execute($tableValues);





share|improve this answer






















  • thank you very much for your help and advice
    – Kashmir96
    Nov 12 at 4:03














up vote
1
down vote



accepted










As you are effectively trying to map $record to your $rego_columns, I suggest using array_map to retrieve the values.



Then you can use implode to add the wrapping quotes or backticks around the array values.



Example https://3v4l.org/h70pO



$rego_columns = [
"make",
"model",
"year",
"rego",
];

$record = ['make' => 'A', 'model' => 'B', 'year' => 'C', 'rego' => 'D'];

$tableValues = array_map(function($r) use ($record)
return $record[$r];
, $rego_columns);

$tableColumns = '`' . implode('`,`', $rego_columns) . '`';
$tableValues = '"' . implode('","', $tableValues) . '"';


echo 'INSERT INTO table_name (' . $tableColumns . ') VALUES (' . $tableValues . ')';


Results in



INSERT INTO table_name (`make`,`model`,`year`,`rego`) VALUES ("A","B","C","D");



If you needed the dots included around the table column values for some reason, change the implode to:



$tableColumns = '`.' . implode('.`,`.', $rego_columns) . '.`';
$tableValues = '"' . implode('","', $tableValues) . '"';


Results in: https://3v4l.org/1DI76



INSERT INTO table_name (`.make.`,`.model.`,`.year.`,`.rego.`) VALUES ("A","B","C","D")



As a side note, I strongly suggest using prepared statements whenever using variable data with a database. And adopting this to map the values to the placeholders.



Example https://3v4l.org/kcl4m



$tableValues = array_map(function($r) use ($record) 
return $record[$r];
, $rego_columns);
$placeholders = implode(',', array_fill(0, count($tableValues), '?'));
$tableColumns = '`' . implode('`,`', $rego_columns) . '`';

$query = 'INSERT INTO table_name (' . $tableColumns . ') VALUES(' . $placeholders . ')';

$stmt = $pdo->prepare($query);
$stmt->execute($tableValues);





share|improve this answer






















  • thank you very much for your help and advice
    – Kashmir96
    Nov 12 at 4:03












up vote
1
down vote



accepted







up vote
1
down vote



accepted






As you are effectively trying to map $record to your $rego_columns, I suggest using array_map to retrieve the values.



Then you can use implode to add the wrapping quotes or backticks around the array values.



Example https://3v4l.org/h70pO



$rego_columns = [
"make",
"model",
"year",
"rego",
];

$record = ['make' => 'A', 'model' => 'B', 'year' => 'C', 'rego' => 'D'];

$tableValues = array_map(function($r) use ($record)
return $record[$r];
, $rego_columns);

$tableColumns = '`' . implode('`,`', $rego_columns) . '`';
$tableValues = '"' . implode('","', $tableValues) . '"';


echo 'INSERT INTO table_name (' . $tableColumns . ') VALUES (' . $tableValues . ')';


Results in



INSERT INTO table_name (`make`,`model`,`year`,`rego`) VALUES ("A","B","C","D");



If you needed the dots included around the table column values for some reason, change the implode to:



$tableColumns = '`.' . implode('.`,`.', $rego_columns) . '.`';
$tableValues = '"' . implode('","', $tableValues) . '"';


Results in: https://3v4l.org/1DI76



INSERT INTO table_name (`.make.`,`.model.`,`.year.`,`.rego.`) VALUES ("A","B","C","D")



As a side note, I strongly suggest using prepared statements whenever using variable data with a database. And adopting this to map the values to the placeholders.



Example https://3v4l.org/kcl4m



$tableValues = array_map(function($r) use ($record) 
return $record[$r];
, $rego_columns);
$placeholders = implode(',', array_fill(0, count($tableValues), '?'));
$tableColumns = '`' . implode('`,`', $rego_columns) . '`';

$query = 'INSERT INTO table_name (' . $tableColumns . ') VALUES(' . $placeholders . ')';

$stmt = $pdo->prepare($query);
$stmt->execute($tableValues);





share|improve this answer














As you are effectively trying to map $record to your $rego_columns, I suggest using array_map to retrieve the values.



Then you can use implode to add the wrapping quotes or backticks around the array values.



Example https://3v4l.org/h70pO



$rego_columns = [
"make",
"model",
"year",
"rego",
];

$record = ['make' => 'A', 'model' => 'B', 'year' => 'C', 'rego' => 'D'];

$tableValues = array_map(function($r) use ($record)
return $record[$r];
, $rego_columns);

$tableColumns = '`' . implode('`,`', $rego_columns) . '`';
$tableValues = '"' . implode('","', $tableValues) . '"';


echo 'INSERT INTO table_name (' . $tableColumns . ') VALUES (' . $tableValues . ')';


Results in



INSERT INTO table_name (`make`,`model`,`year`,`rego`) VALUES ("A","B","C","D");



If you needed the dots included around the table column values for some reason, change the implode to:



$tableColumns = '`.' . implode('.`,`.', $rego_columns) . '.`';
$tableValues = '"' . implode('","', $tableValues) . '"';


Results in: https://3v4l.org/1DI76



INSERT INTO table_name (`.make.`,`.model.`,`.year.`,`.rego.`) VALUES ("A","B","C","D")



As a side note, I strongly suggest using prepared statements whenever using variable data with a database. And adopting this to map the values to the placeholders.



Example https://3v4l.org/kcl4m



$tableValues = array_map(function($r) use ($record) 
return $record[$r];
, $rego_columns);
$placeholders = implode(',', array_fill(0, count($tableValues), '?'));
$tableColumns = '`' . implode('`,`', $rego_columns) . '`';

$query = 'INSERT INTO table_name (' . $tableColumns . ') VALUES(' . $placeholders . ')';

$stmt = $pdo->prepare($query);
$stmt->execute($tableValues);






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 at 2:08

























answered Nov 12 at 1:21









fyrye

8,39513549




8,39513549











  • thank you very much for your help and advice
    – Kashmir96
    Nov 12 at 4:03
















  • thank you very much for your help and advice
    – Kashmir96
    Nov 12 at 4:03















thank you very much for your help and advice
– Kashmir96
Nov 12 at 4:03




thank you very much for your help and advice
– Kashmir96
Nov 12 at 4:03

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254753%2fforeach-with-different-final-loop%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3

Museum of Modern and Contemporary Art of Trento and Rovereto