Show summary if php loop? - php

I have a loop that looks like this:
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
}
}
How do I turn this:
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
into a code that will show something like:
XX inputted successfully
{list of schools with ID listed here}
XX not inpputed due to errors
{list of schools not inputted}
Would like to see a simple summary of the entire loop rather than seeing a repeated result of each loop that occurred.

Collect all the information you want in variables, and print them at the end.
$success = $fail = "";
$success_count = $fail_count = 0;
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query)) {
$success .= "<li>" . $Row['school_name'] . "</li>";
$success_count++;
} else {
$fail .= "<li>" . $Row['school_name'] . "</li>";
$fail_count++;
}
}
}
echo $success_count . " inputted successfully:<br><ul>" . $success . "</ul>";
echo $fail_count . " not inputted due to errors:<br><ul>" . $fail . "</ul>";
Replace $Row['school_name'] with whatever the correct variable is for the school name in your data.

Related

PHP syntax only store last value of the array

need help with this syntax it only stores the last value of my array into the database.
<?php
if(isset($_POST["submit"])) {
$lines=preg_split('/\r\n|[\r\n]/', $_POST['text']);
foreach($lines as $line => $value)
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}
?>
You should add bracket to your foreach. Without that, only the next line will be in the loop.
so you should have:
foreach($lines as $line => $value) {
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
}
}
I advice you to use bracket for all your conditions and loops since the readability is better and you avoid errors like that.
foreach($lines as $line => $value) { // Add braces near foreach
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}// close foreach

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

sqlsrv_fetch_object() not returning results

I have a simple SELECT statement, an optional WHERE clause, and an ORDER BY however while looping through sqlsrv_fetch_object() I am not getting any records:
if (!$conn)
{
echo "no connection!\n";
}
$data = array();
$qry = "SELECT DISTINCT lineid, ord_num, prod_num, description, prod_type, style, color, sizetype, qty1, qty2, qty3, qty4, qty5, qty6, qty7, qty8, qty9, qty10, qty11, qty12, qty13, qty14, qty15, ext_id, decoration1, design1, iposition1, cccode1, decoration2, design2, iposition2, cccode2, decoration3, design3, iposition3, cccode3, '', design4, iposition4, cccode4, decoration5, design5, iposition5, cccode5, decoration6, design6, iposition6, cccode6, decoration7, design7, iposition7, cccode7, last_mod FROM DataLIVE.dbo.sodetail ";
if ($last_run_date)
{
$qry .= "WHERE last_mod > '" . $last_run_date . "' ";
}
$qry .= "ORDER BY last_mod ASC";
fwrite($fp, $qry . "\n");
if ($st = sqlsrv_query($conn, $qry))
{
while ($row = sqlsrv_fetch_object($st))
{
$row->last_mod = $row->last_mod->format('Y-m-d H:i:s');
fwrite($fp, "Last Mod::: " . $row->last_mod . "\n");
$data[] = $row;
}
sqlsrv_free_stmt($st);
unset($row, $st);
}
else
{
$sqlerr = sqlsrv_errors();
foreach ($sqlerr as $key)
{
foreach ($key as $col => $val)
{
echo "Error Key: " . $col . "\nError Msg: " . $val . "\n";
fwrite($fp, "Error Key: " . $col . "\nError Msg: " . $val . "\n");
}
}
$data = FALSE;
}
return $data;
I don't know why sqlsrv_fetch_object() is not returning anything. Also, I can copy and paste the query directly into SQL Server Studio from the log I'm writing, it parses fine. There is nothing in my log file where I am writing out the last_mod date in the while loop.
I posted this with a slightly different question a few minutes ago and someone suggested to remove the selection of an empty string in the SELECT statement, but I need that empty string placeholder there where it is.

Inserting multiple fields with a similar name

I have a form I'm using to send multiple fields with a similar name but using square brackets to send them as an array with the key being 'id'. I am able to loop through successfully using a foreach loop but my insert query fails to make any changes in the db.any clues as to why?
here is the code from the form:
$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];
while ($music = mysql_fetch_array($allmusic)) {
echo "<td class=\"td20 tdblue\">
<input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
</td>";
}
and here is the code on my form processor
foreach ($_POST['song_title'] as $id => $song) {
$query = "UPDATE music SET
song_title = '{$song}'
WHERE id = $id ";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
Try this.
Also watch for security http://www.phptherightway.com/#data_filtering
foreach ($_POST['song_title'] as $id => $song) {
$id = (int) $id;
$song = mysql_real_escape_string($song);
$query = "UPDATE music SET
song_title = '$song'
WHERE id = $id LIMIT 1;";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}

Categories