php foreach循环插入数据反馈每次重复

this is my php code. hire is a problem i use check box selection and insert data in my database. but it insert data by foreach loop. so when press ok if data successfully insert then for 3 selection it say

successfully register successfully register successfully register but i want it say only once successfully register


    $db=require "script_database/connect.php";  
    $query = "SELECT * FROM course";
    $query1="select * from selection where student_id='1229CSE00241' and semester='FALL2015' ";

            echo "you already selected courses for registration";

    else if($_POST['buy']==''){
    echo "<h2><center>You didn't select any courses</h2></center>";

    foreach($_POST['buy'] as $item) {

    $query = "SELECT * FROM course WHERE id = $item

    if ($r = mysql_query($query)) { 

        while ($row = mysql_fetch_array($r)) {


    } else { 
        print '<p style="color: blue">Error!</p>';


    $insert_query="insert into selection(student_id,semester,course_id,course_title,course_credits,course_status,date_time) values ('$student_id','$semester','$course_id','$course_title','$course_credits','$course_status',NOW())";

    //here is my problem 
    //it repeat every time when insert data but i want to make it only once

    echo "successfully register";
    echo "problem show";




在开始 foreach </ code>循环之前,设置一个标志,如:</ p>

  $ error = false; 
</ code> </ pre>

然后在循环中</ p>

  if(!mysql_query($  insert_query))
$ error = true;
</ code> </ pre>

循环结束后</ p>

   if($ error){
</ code> </ pre>
</ div>



Before you start your foreach loop set a flag like:

 $error = false;

Then in your loop

    $error =true;

And after the loop has closed

   echo "problem show";
   echo "successfully register";

Csdn user default icon
php foreach循环嵌套增加重复

<div class="post-text" itemprop="text"> <p>I've got a loop nested in a loop. All of the data displays fine until I get to the second loop and the returned data keeps repeated. It gets to the point where songs of the items from the second loop gets repeated over 15 times. </p> <p>item -subitems</p> <p>item -subitems -subitems</p> <p>item -subitems -subitems -subitems </p> <p>item -subitems -subitems -subitems -subitems </p> <p>I was told to clear my loop but I'm sure how to do that. Any ideas? here's a live example if need: view-source:<a href="" rel="nofollow"></a></p> <pre><code>&lt;?php include ("connection.php"); foreach($db-&gt;query("SELECT * FROM mixtapes WHERE year='2014' OR year = '2015' ORDER BY id DESC LIMIT 24") as $info) { echo "mixtape-".$info['id']," { "; echo "\t\"id\" : \"".$info['id']."\", "; echo "\t\"title\" : \"".$info['title']."\", "; echo "\t\"name\" : \"".$info['name']."\", "; echo "\t\"genre\" : \"".$info['genre']."\", "; echo "\t\"year\" : \"".$info['year']."\", "; echo "\t\"downloads\" : \"".$info['downloads']." Downloads\", "; echo "\t\"thumb\" : \"".$info['thumb']."\", "; echo "\t\"songs\" : { "; if ($handle = opendir("mixtapes/zip/".$info['id'])) { while (false !== ($entry = readdir($handle))) { if ($entry != "mixtapes/zip/".$info['id'] &amp;&amp; $entry != "mixtapes/zip/".$info['id']) { if ($newhandle = opendir("mixtapes/zip/".$info['id']."/".$entry)) { while (false !== ($newentry = readdir($newhandle))) { if ($newentry != "mixtapes/zip/".$info['id']."/".$entry &amp;&amp; $newentry != "mixtapes/zip/".$info['id']."/".$entry) { $ext = substr($newentry, strrpos($newentry, '.') + 1); if ($ext == "mp3" || $ext == "m4a") { $item = "mixtapes/zip/".$info['id']."/".$entry."/"; $musicarray[] = $newentry; sort($musicarray); } } } closedir($newhandle); } } } closedir($handle); } foreach ($musicarray as $song) { echo "\t\t\"track\" : \"$item$song\", "; } echo "\t} "; echo "}, "; }?&gt; </code></pre> </div>

php foreach循环插入两个表

<div class="post-text" itemprop="text"> <p>I want to insert the array into table.</p> <p>Each name can have multiple addresses.</p> <p><code>Name</code> will be in <code>table1</code> and all the addresses will be in another <code>table2</code> corresponding to the <code>name</code></p> <p>my array is below:</p> <pre><code>array ( [name] =&gt; Array ( [0] =&gt; jack [1] =&gt; jill [2] =&gt; tom ) [address] =&gt; Array ( [0] =&gt; array ( [0] =&gt; jack_aadress1 [1] =&gt; jack_aadress2 [2] =&gt; jack_aadress3 ) [1] =&gt; array( [0] =&gt; jill_address1 [1] =&gt; jill_address2 [2] =&gt; jill_address3 ) [2] =&gt; array( [0] =&gt; tom_address1 [1] =&gt; tom_address2 [2] =&gt; tom_address3 ) ) </code></pre> <p>Below is the one I tried:</p> <pre><code>foreach($_REQUEST['room_name'] as $key=&gt;$value) { mysql_query("insert into table1(name) values($value)"); $insert_id = mysql_insert_id(); foreach($_REQUEST['address'] as $key1=&gt;$value1) { mysql_query("insert into table2(id,address) values($insert_id,$value1)"); } } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I was inserting records successfully with this code:</p> <pre><code> foreach($R as $k=&gt;$v) { $test_id = str_replace('rep_result_', '', $k); if(strstr($k, 'rep_result_')) { $content = $v; $SQL = "INSERT INTO report SET rep_te_id = '$test_id', rep_result = '$content', record_id = '$R[payment_id]', rep_date = '$dt'"; </code></pre> <p>But now I have two extra fields in my table, <code>remark</code> and <code>nor</code>. So now, for inserting all data I made this code:</p> <pre><code>foreach($R as $k=&gt;$v) { $test_id = str_replace('rep_result_', '', $k); if(strstr($k, 'rep_result_')) { $content = $v; if(strstr($k, 'remark_')) { $remark=$v; if(strstr($k, 'nor_')) { $nor=$v; $SQL = "INSERT INTO report SET rep_te_id = '$test_id', rep_result = '$content', record_id = '$R[payment_id]', remark = '**$remark**', nor = '**$nor**', rep_date = '$dt'"; </code></pre> <p>I did not get anything in the database. Not everything is ok here. If I use only one <code>if</code> condition then data is being inserted like <code>(rep_result,remark,nor any one)</code>.</p> <pre><code>if(strstr($k, 'remark_')) $remark=$v; </code></pre> <p>But when I use all the three condition, nothing is stored. I know I have <code>if</code>statement or <code>foreach</code> loop problem.</p> </div>


<div class="post-text" itemprop="text"> <p>I have an array: <code>$product_counts = array_count_values($product_array);</code></p> <p>The keys for this array are merchant ID's and the values are integers (product counts). So if I was to write the following code:</p> <pre><code>foreach($product_counts as $key =&gt; $value){ echo "key: $key"; echo "value: $value"; } </code></pre> <p>I would get the following (which is what I want): </p> <pre><code>key: 26816928 value: 13 key: 26816931 value: 2 ... X the amount of indexes in the array. </code></pre> <p>However if I was to write the following code: </p> <pre><code>foreach($product_counts as $key =&gt; $value){ mysql_query("INSERT INTO merchantinfo(ProductCount) VALUES $value WHERE MerchantID = $key"); } </code></pre> <p>The values of the $value variable don't go into the field where MerchantID = $key....instead the tuples just default to null, which is what I've set them to do. I believe this could be a case of needing to type cast the variable as integers .... but I'm in general quite lost with this. </p> <p>Thanks in advance</p> </div>

在数据库中发布一个php foreach循环,数据插入错误

<div class="post-text" itemprop="text"> <p>I have a cart where all my products are generated inside of a foreach loop that stores them in sessions. And i want to post each product in my Table:orders. But i am getting some errors.</p> <p><em>Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 46</em></p> <p><em>Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 54</em></p> <p>what i am trying to post...</p> <pre><code>Array ( [numero] =&gt; Array ( [0] =&gt; 1 [1] =&gt; 1 [2] =&gt; 1 [3] =&gt; 1 ) [vari] =&gt; Array ( [0] =&gt; [1] =&gt; 1 [2] =&gt; 2 [3] =&gt; 3 ) [desenho] =&gt; Array ( [0] =&gt; img/1.0.png [1] =&gt; img/1-1.png [2] =&gt; img/1-2.png [3] =&gt; img/1-3.png ) [fabric] =&gt; Array ( [0] =&gt; 1 [1] =&gt; 4 [2] =&gt; 2 [3] =&gt; 2 ) [size] =&gt; Array ( [0] =&gt; 45 [1] =&gt; 45 [2] =&gt; 45 [3] =&gt; 50 ) [qnty] =&gt; Array ( [0] =&gt; 1 [1] =&gt; 1 [2] =&gt; 1 [3] =&gt; 1 ) //some other arrays [submit_post] =&gt; Enviar ) </code></pre> <p>This is my <a href="" rel="nofollow">foreach loop code</a></p> <p>I am trying to post this way...</p> <pre><code>if(isset($_POST['submit_post'])){ $date = date('Y-m-d'); $size = isset($_POST['size']) ? $_POST['size'] : array(); $numero = isset($_POST['numero']) ? $_POST['numero'] : array(); $vari = isset($_POST['vari']) ? $_POST['vari'] : array(); $desenho = isset($_POST['desenho']) ? $_POST['desenho'] : array(); $fabric = isset($_POST['fabric']) ? $_POST['fabric'] : array(); $size = isset($_POST['size']) ? $_POST['size'] : array(); $qnty = isset($_POST['qnty']) ? $_POST['qnty'] : array(); $cost = isset($_POST['cost']) ? $_POST['cost']: array(); $subtotal = isset($_POST['subtotal']) ? $_POST['subtotal'] : array(); $total = isset($_POST['total']) ? $_POST['total'] : array(); $all_products = isset($_POST['all_products']) ? $_POST['all_products'] : array(); $subT=0; $pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName']; //46 $query = "SELECT * FROM almofadas WHERE id_price='$fabric'"; $result = mysqli_query($conn,$query); while($rows = mysqli_fetch_assoc($result)){ $tecido=$rows['tecido']; } $ins_sql = "INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal) //54 VALUES ('$fabric', '$size' , '$qnty', '$pedido', '$desenho', '$numero', '$vari', '$cost', '$subT')"; if ($conn-&gt;query($ins_sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " ; } $conn-&gt;close(); } </code></pre> <p>What i am doing wrong,how i will fix this?</p> </div>


<div class="post-text" itemprop="text"> <p>How to insert multiple arrays with a foreach in rows of databases?</p> <p>It's not a problem with an array, but my problem is to use two arrays or more.</p> <p>my php code:</p> <pre><code>$checkBox1 = implode(',', $_POST['goinput1']); $checkBox2 = implode(',', $_POST['goinput3']); $mark3=explode(',', $checkBox1); $mark4=explode(',', $checkBox2); foreach($mark3 as $out3) { $sql_sub = "INSERT INTO sub_forms (bord_mizban,bord_mihman) VALUES ('$out3','$out4')"; if ($conn-&gt;query($sql_sub) === TRUE) { } else { } } </code></pre> <p>** <strong>I want the out 4 variable insert to the database with the out 3 variable</strong> **</p> </div>


<div class="post-text" itemprop="text"> <p>hello all i have about 5 array having same no of elements and i want to insert them for each value of array into database like</p> <pre><code> $array1 has 3 elements a1,a2,a3 $array2 has 3 elements b1,b2,b3 $array3 has 3 elements c1,c2,c3 now i want to insert data into database like field1=a1,field2=b1,field3=c1 and similery for all the values saparete entry will be there </code></pre> <p>please help me achieve this i know this can be done by foreach loop of php</p> </div>

foreach循环插入列表项的$ id

<div class="post-text" itemprop="text"> <p>I try to develop a simple comment system. The foreach row <code>$result</code> contains variables from a database named posts. </p> <p>The id of the post(every post is a list item) that is AUTO_INCREMENT and every post have a unique $id, the author of the post and the comment become submitted to a file that insert the three values into a database named comments. </p> <p>The second foreach loop, <code>$comments</code>, should show the comments when the user click the popup button. That does not works because the id <code>&lt;input type="hidden" name="id" id="id" value="&lt;?PHP echo $row['id']; ?&gt;" type="text" /&gt;</code> wont become right inserted(comments.php should do that). </p> <p>The result is that all comments become showed in every list item and not the only these comments who are e.g. at list item 2. How can I insert the $id of the list items into the database?</p> <pre><code>&lt;div data-role="content"&gt; &lt;?php include( "list.php"); ?&gt; &lt;div data-demo-html="true"&gt; &lt;ul data-role="listview" data-inset="true" class="ui-listview ui-listview-inset ui-corner-all ui-shadow"&gt; &lt;?php foreach ($result as $key=&gt; $row): ?&gt; &lt;li id="listone" name="listone" data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-bar-b ui-li-has-count ui-first-child"&gt; &lt;?php echo $row[ 'date']; ?&gt; &lt;/li&gt; &lt;li data-corners="false" data-shadow="false" data-iconshadow="true" data-wrapperels="div" data-icon="arrow-r" data-iconpos="right" data-theme="a"&gt; &lt;div class="ui-btn-inner ui-li"&gt; &lt;div class="ui-btn-text"&gt; &lt;a class="ui-link-inherit"&gt; &lt;p class="ui-li-aside ui-li-desc"&gt;&lt;strong&gt;&lt;/strong&gt; &lt;?php echo $row[ 'time']; ?&gt; &lt;/p&gt; &lt;p class="ui-li-desc"&gt;&lt;strong&gt;&lt;?php echo $row['title']; ?&gt;&lt;/strong&gt; &lt;/p&gt; &lt;p class="ui-li-desc"&gt; &lt;?php echo $row[ 'text']; ?&gt; &lt;/p&gt; &lt;p class="ui-li-desc"&gt;&lt;strong&gt;&lt;?php echo $row['town']; ?&gt;&lt;/strong&gt; &lt;/p&gt; &lt;a href="#popupcomment" data-rel="popup" data-position-to="window" data-transition="pop"&gt;comment&lt;/a&gt; &lt;div data-role="popup" id="popupcomment" data-theme="a" class="ui-corner-all"&gt; &lt;form data-ajax="false" name="login-form" class="login-form" action="./comments.php" method="post" style="padding:20px 40px;"&gt; &lt;div class="content"&gt; &lt;?php include( "showcomments.php"); ?&gt; &lt;?php foreach ($comments as $keyComment=&gt; $rowComment): ?&gt; &lt;p class="ui-li-desc"&gt;&lt;strong&gt;&lt;?php echo $rowComment['username']; ?&gt;&lt;/strong&gt; &lt;/p&gt; &lt;p class="ui-li-desc"&gt; &lt;?php echo $rowComment[ 'comment']; ?&gt; &lt;/p&gt; &lt;?php endforeach; ?&gt; &lt;input type="hidden" name="id" id="id" value="&lt;?php echo $row['id']; ?&gt;" type="text" /&gt; &lt;input type="hidden" name="autorpost" id="autorpost" value="&lt;?php echo $row['autor']; ?&gt;" type="text" /&gt; &lt;!-- autor des posts --&gt; &lt;textarea rows="1" name="text" id="text" class="foo"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="footer"&gt; &lt;input type="submit" name="save" value="comment" class="button" data-theme="a" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- div content --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <blockquote> <p>showcomments.php:</p> </blockquote> <pre><code>$hostname='localhost'; $user='root'; $password=''; $id = $row['id']; try { $dbh = new PDO("mysql:host=$hostname;dbname=searchfood",$user,$password); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // &lt;== add this line $sql = "SELECT id, username, comment, time FROM comments WHERE id_post = $id ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen if ($com = $dbh-&gt;query($sql)) {// need to add this line in your code // then after fetchColumn $comments = $com-&gt;fetchAll(); } } catch(PDOException $e) { echo $e-&gt;getMessage(); } </code></pre> <blockquote> <p>comments.php:</p> </blockquote> <pre><code>$hostname='localhost'; $user='root'; $password=''; if(isset($_POST["id"])){ try { $dbh = new PDO("mysql:host=localhost;dbname=searchfood", $user, $password); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // &lt;== add this line // prepare your query $query = 'INSERT INTO comments (username, autorpost, comment, id_post, time) VALUES (?, ?, ?, ?, now())'; $stmt = $dbh-&gt;prepare($query); // bind variables $stmt-&gt;execute(array($_COOKIE['username'], $_POST['autorpost'], $_POST['text'], $_POST['id'])); // pull last insert id $new = $dbh-&gt;lastInsertId(); // show success message or redirect, whatever you want echo "New Record Inserted Successfully"; $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['username']) . ') wurde angelegt, &lt;a href="login.php"&gt;weiter zur Anmeldung&lt;/a&gt;.'; header("Location: http://".$_SERVER['HTTP_HOST']."/lendsth/main.php", true, 302); } catch(PDOException $e) { echo $e-&gt;getMessage(); } } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I want to prepare json with php as follows. But, the services section does not occur nested. How can I get json output as below by correcting php code?</p> <pre><code>foreach($this-&gt;input-&gt;post('name') as $key =&gt; $value){ $services = []; foreach($this-&gt;input-&gt;post('services') as $value2){ $services[] = array( 'service_name' =&gt; $value2 ); } $json[] = array( 'name' =&gt; $this-&gt;input-&gt;post('name')[$key], 'surname' =&gt; $this-&gt;input-&gt;post('surname')[$key], 'birthday' =&gt; $this-&gt;input-&gt;post('birthday')[$key], 'services' =&gt; $services ); } echo json_encode($json); </code></pre> <p>I want this:</p> <pre><code>[ { "name":"aa", "surname":"bb", "birthday":"10.07.2019", "services":[ { "service_name":"test1", "service_name":"test2", }, ] }, { "name":"cc", "surname":"dd", "birthday":"20.07.2019", "services":[ { "service_name":"test3", "service_name":"test4", }, ] } ] </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I've found weird behaviour in PHPs foreach loop. When I do it like this:</p> <pre><code>&lt;?php $arr = array(); foreach ( $arr as $a ) { echo 'Hello'; } ?&gt; </code></pre> <p>Then as I expect, nothing is printed simply because the array is empty, but when I do it like this:</p> <pre><code>&lt;? $arr = array(); ?&gt; &lt;? foreach ( $arr as $a ): ?&gt; Hello &lt;? endforeach; ?&gt; </code></pre> <p>Then the word 'Hello' is printed once... Even though the array is empty. I don't see why this would behave differently. To me this looks like a bug, but I could be missing something...</p> <p>I'm using PHP 5.4 (Windows).</p> <p>And in case you're wondering, I'm using the second method in my .phtml files (template files).</p> </div>


<div class="post-text" itemprop="text"> <p>I have a drag and drop JS plugin that saves strings as the following:</p> <pre><code>["кровать","бегемот","корм","валик","железосталь"] </code></pre> <p>I have found that I can use str_replace in an array to remove both brackets and " char. The issue that I now have is that I have a invalid argument for passing through the foreach loop as it cannot distinguish each individual word. </p> <pre><code>$bar = '["кровать","бегемот","корм","валик","железосталь"]'; $new_str = str_replace(str_split('[]"'), '', $bar); foreach($new_str as $arr){ echo $arr; } </code></pre> <p>So the data now outputted looks as follows (if I were to echo before the foreach loop):</p> <pre><code>кровать,бегемот,корм,валик,железосталь </code></pre> <p>Is there anyway in which I can use a comma as a delimeter to then pass this through the foreach, each word being it's own variable?</p> <p>Is there an easier way to do this? Any guidance greatly appreciated!</p> </div>


<div class="post-text" itemprop="text"> <p>I am using foreach loop for insertion query. At the same time I am matching value if those are exist in database or not. If value exist than I want to skip that particular key and than move to next key value to insert. Again it check if value exist or not than save record if values are not exist in database.</p> <p>I have used following approach to do this.</p> <pre><code>foreach( $inputs as $key =&gt; $value) { if ($key == 'empty') continue; $check=mysql_query("select * from from t_atc_list where s_title='$key' and r_name='$value'"); if(mysql_num_rows($check)!=0){ continue; } $result = mysql_query("INSERT into t_atc_list(a_name, s_title, r_name) values('$album','$key', '$value')")or die(mysql_error()); echo "&lt;strong&gt;$key&lt;/strong&gt; Singer &lt;strong&gt;$value&lt;/strong&gt;&lt;/br&gt;"; } </code></pre> <p><strong>NOTE :</strong> (1). Values are inserting if value are already present that is duplicate entries. (2). I am getting warning " mysql_num_rows(): supplied argument is not a valid MySQL result resource in..."</p> </div>


![图片说明]( 这样一个数组,如何三个字段为一条数据循环插入数据库?


<div class="post-text" itemprop="text"> <p>i have this long form that requires multiple inputs, how can i properly insert these inputs into an array using a foreach loop?</p> <p>assuming i have these:</p> <pre><code>$name = $_POST['name']; $color = $_POST['color']; $age= $_POST['age']; $gender = $_POST['gender']; $location = $_POST['location']; ...etc.. </code></pre> <p>instead of typing such this..</p> <pre><code>$myarray = array('id'=&gt;$id,'name'=&gt;$name,'color'=&gt;$color,'age'=&gt;$age,'gender'=&gt;$gender,'location'=&gt;$location,etc...); </code></pre> <p>how can i let <code>foreach</code> loop insert the appropriate values into the array? </p> </div>


<div class="post-text" itemprop="text"> <p>I have an input form with two values as a key, constructed this way:</p> <pre><code>&lt;input name="verificarPago['.$x['pagoID'].'-'.$x['userID'].']" type="text"&gt; </code></pre> <p>So, the HTML would look like, for example, like this:</p> <pre><code>&lt;input name="verificarPago[4-10]" type="text"&gt; </code></pre> <p>Besides that I have the value that the user can type, for example "Juan".</p> <p><strong>The inputs are created programmatically, and I want to save them each three values (in the example: 4, 10, Juan) into a database.</strong></p> <p>So, when the user submits the form, I thought on using <code>foreach</code> in order to access the elements in that array, but my problem is: How may I explode the keys to access the two values separately?</p> <p>I've tried this (I'm not taking into account security now, I'm trying to prove the concept):</p> <pre><code> $verificar = $_POST['verificarPago']; foreach ($verificar as $pago =&gt; $curso) { //I'm pretty much stuck here. $verificar= array_flip(explode("-", $verificar)); //I want to insert the three items into the database $verificarPago = "INSERT pagosVerificados SET userID = '$usuario', pagoID = '$pago', cursoID = '$curso'"; $cargarPago = mysqli_query($conectar, $verificarPago); } </code></pre> <p>I've tried adding to the form another input type, so the values wouldn't be together, but that way I should do a foreach inside a foreach and that renders duplicated results (and with errors as well).</p> </div>


<div class="post-text" itemprop="text"> <p>Good afternoon. I want to scrobble tracks from the radio, but I have a problem with my code which runs with Cron: </p> <pre><code>&lt;?php header( 'Content-type: text/html; charset=UTF-8' ); function compareFiles( $file_a, $file_b ) { if ( filesize( $file_a ) == filesize( $file_b ) ) { $fp_a = fopen( $file_a, 'rb' ); $fp_b = fopen( $file_b, 'rb' ); while ( ( $b = fread( $fp_a, 4096 ) ) !== false ) { $b_b = fread( $fp_b, 4096 ); if ( $b !== $b_b ) { fclose( $fp_a ); fclose( $fp_b ); return false; } } fclose( $fp_a ); fclose( $fp_b ); return true; } return false; } if ( compareFiles( "/var/log/icecast2/playlist.log", "/home/playlist.log" ) == false ) { copy( "/var/log/icecast2/playlist.log", "/home/playlist.log" ); $file = file( "/home/playlist.log" ); $file_array = $file; $far = array_slice( $file, -2 ); $far = array_reverse( $far ); $dsz = print_r( $far ); file_put_contents( $dsz, '/home/arr.txt' ); foreach ( $far as $arr1 =&gt; $arr2 ) { $elem = explode( '|', $arr2 ); $is_low = strpos( $arr2, 'hcore_48' ); if ( $is_low != true ) { // $c = date_create_from_format('', $elem[0]); // $time= $c-&gt;format('H:m'); $song = $elem[ 3 ]; $infos_artist = explode( ' - ', $song ); $infos_artist[ 0 ] = trim( $infos_artist[ 0 ] ); $infos_artist[ 1 ] = trim( $infos_artist[ 1 ] ); if ( $infos_artist[ 0 ] != "HCore FM" ) { $partnerId = "xxx"; $partnerKey = "xxx"; $stationId = "xxx"; $artist_tunein = str_replace( ' ', '+', $infos_artist[ 0 ] ); $title_tunein = str_replace( ' ', '+', $infos_artist[ 1 ] ); $commercial = false; if ( ( $infos_artist[ 0 ] == "HCore FM" ) || ( $infos_artist[ 0 ] == "Promo" ) ) $commercial = true; $url_tunein = "" . $partnerId . "&amp;partnerKey=" . $partnerKey . "&amp;id=" . $stationId . "&amp;title=" . $title_tunein . "&amp;artist=" . $artist_tunein . "&amp;commercial=" . $commercial; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url_tunein ); curl_setopt( $ch, CURLOPT_HEADER, 1 ); curl_setopt( $ch, CURLOPT_POST, 1 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_POSTFIELDS, "&amp;title=" . $title_tunein . "&amp;artist=" . $artist_tunein . "&amp;commercial=" . $commercial ); $data = curl_exec( $ch ); $server_output = simplexml_load_string( $data ); curl_close( $ch ); $log = "/home/tuneinlog.txt"; $url = "" . $artist_tunein . "+-+" . $title_tunein . "&amp;count=1&amp;access_token=932fe2e4fc4e89179bdeb223f382394a43684125d7ebdb3382878866d190cef8f2bb6352d0efe82d64057"; $result = file_get_contents( $url ); // Will dump a beauty json :3 $obj = json_decode( $result, true ); $vk = "/home/vklog.txt"; if ( $result == "{\"response\":[0]}" ) { file_put_contents( $vk, PHP_EOL . $artist_tunein . " - " . $title_tunein . " ", FILE_APPEND ); } $aid = $obj[ 'response' ][ '1' ][ 'aid' ]; $oid = $obj[ 'response' ][ '1' ][ 'owner_id' ]; $urlnh = "" . $oid . "_" . $aid . "&amp;target_ids=-91685382&amp;access_token=xxx"; $res = file_get_contents( $urlnh ); } break; } } } ?&gt; </code></pre> <p>One line from file, but foreach works many times (5-6 or 15-16). Why? I want to make foreach work only 1 time. Please help me. What's the problem? </p> <p><strong>update</strong></p> <p>contents of <code>var_dump($far)</code></p> <pre><code>Array ( [0] =&gt; 03/Aug/2015:18:00:46 +0300|/hcore_128|1|The Union Underground - Call Me (Blondie cover) [1] =&gt; 03/Aug/2015:18:00:47 +0300|/hcore_48|0|The Union Underground - Call Me (Blondie cover) ) </code></pre> </div>

(PHP)foreach循环没有正确地将我的所有行插入到MYSQL DB中

<div class="post-text" itemprop="text"> <p>I have an api which pulls a master list of property listings from a real estate association. When I make the request I get back I .txt file of all the results in my request; this is in a XML structure, I am happy with this because all the results I should get are there. However I also wish to download the listings into a MYSQL DB. This is where I am getting issues. The way the api works that you can only request 100 listings at a time. So you have to build a loop that loops the amount of time of than amount of results you got back divided by 100. Then inside that loop have another loop which loops 100 times(the limit)to pull the listings. So when inside my inner loop which is a foreach loop, I am getting issues, or at least I think its there.</p> <p>The issue is confusing to me cause when I was doing my testing and i echoed $i and $j within the inner loop and everything counted up fine j went from 0 to 1900 as it should so it does go through each result. Just when I try to use those results for say an echo or DB they dont all seem to be there.</p> <p>Any help would be much appreciated. I ll try to add just the relevant parts of my scripts rather than my whole scripts. </p> <pre><code>$TimeBackPull = "-9 months"; error_log("-----GETTING ALL ID's-----"); $DBML = "(LastUpdated=" . date('Y-m-d', strtotime($TimeBackPull)) . ")"; $params = array("Limit" =&gt; 1, "Format" =&gt; "STANDARD-XML", "Count" =&gt; 1); $results = $RETS-&gt;SearchQuery("Property", "Property", $DBML, $params); $totalAvailable = $results["Count"]; error_log("-----".$totalAvailable." Found-----"); if(empty($totalAvailable) || $totalAvailable == 0) print_r($RETS-&gt;GetLastServerResponse(), true); echo 'total '.$totalAvailable.' &lt;br /&gt;'; for($i = 0; $i &lt; ceil($totalAvailable / $RETS_LimitPerQuery); $i++) { $startOffset = $i*$RETS_LimitPerQuery; error_log("-----Get IDs For ".$startOffset." to ".($startOffset + $RETS_LimitPerQuery).". Mem: ".round(memory_get_usage()/(1024*1024), 1)."MB-----"); $params = array("Limit" =&gt; $RETS_LimitPerQuery, "Format" =&gt; "STANDARD-XML", "Count" =&gt; 1, "Offset" =&gt; $startOffset); $results = $RETS-&gt;SearchQuery("Property", "Property", $DBML, $params); foreach($results["Properties"] as $listing) { echo $listing["AgentDetails"]["@attributes"]["ID"]; } } </code></pre> <p>Another little note is that my ['count'] or in other word the amount of results I get back is what the people i talked to said I should be getting, but the rows inserted or even just echoed never equal up to what It should be</p> </div>

可以在mysql查询中使用php for循环来插入数据吗?

<div class="post-text" itemprop="text"> <pre><code>$insert_additional_info=sprintf("INSERT INTO tbl_additional_info (productid,size_d,size_d1,bags,cartons,retail_price,sales_price,wholesale_price) VALUES (%s, %s,%s, %s,%s,%s,%s,%s)", GetSQLValueString($product_id, "int"), GetSQLValueString($size_d, "int"), GetSQLValueString($size_d1, "int"), GetSQLValueString($bags, "int"), GetSQLValueString($cartons, "int"), GetSQLValueString($retail_price, "int"), GetSQLValueString($sales_price, "int"), GetSQLValueString($wholesale_price, "int")); </code></pre> <p>Instead of INSERTING like above, is there a way that I can use loop inside the VALUES()?</p> <p>The reason is , my output or value to be inserted generated by looping like this.</p> <pre><code>if( isset($_POST['submit']) ) { $_SESSION['myInputs_all'] = array($_POST["myInputs_d"],$_POST["myInputs_d1"],$_POST["myInputs_bags"],$_POST["myInputs_carton"],$_POST["myInputs_retail"],$_POST["myInputs_sales"],$_POST["myInputs_wholesale"]); $counter = count( $_POST['myInputs_d']); $column_array=array('productid,size_d,size_d1,bags,cartons'); for( $c = 0; $c &lt; $counter; $c++ ) { foreach( $myInputs_all as $all_inputs=&gt;$value ) { //This is the output echo $value[$c]; } } } </code></pre> <p>Now, how do I insert echo $value[$c]; inside the VALUES for the INSERT QUERY?</p> <p>I tried something like below but it says Query is empty. But this is how I want to solve it.</p> <pre><code>$insert_additional_info="INSERT INTO tbl_additional_info (productid,size_d,size_d1,bags,cartons) VALUES("; $counter = count( $_POST['myInputs_d']); for( $c = 0; $c &lt; $counter; $c++ ) { foreach( $myInputs_all as $all_inputs=&gt;$value ) { $insert_additional_info.=$value[$c]; $insert_additional_info.=")"; } } </code></pre> </div>

PHP Foreach循环:只向表格插入一次[复制]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php" dir="ltr">Why shouldn't I use mysql_* functions in PHP?</a> <span class="question-originals-answer-count"> 15 answers </span> </li> </ul> </div> <p>I have a image upload Script where I want to insert data into 2 tables. </p> <p>Table: Dresses where description, brand, year will be inserted Table: Images where I insert dress_id and link of the image</p> <p>I have a foreach loop where - in the first loop - the dress and the first image should be inserted, in the second,... loop only the image to table images.</p> <p>Is this possible? I am using mysql_insert_id() is this even possible?</p> <p>Thank you for any assistance and advice!</p> <p>Kind Regards, Stefan</p> <p>here is my code so far.</p> <pre><code>foreach($_FILES['files']['tmp_name'] as $key =&gt; $tmp_name ){ $file_name = $key.$_FILES['files']['name'][$key]; $file_size =$_FILES['files']['size'][$key]; $file_tmp =$_FILES['files']['tmp_name'][$key]; $file_type=$_FILES['files']['type'][$key]; if($file_size &gt; 400097152){ $errors[]='Maximale Filegröße: 100MB'; } $file_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg'; $url = 'dresses/' . $_POST['jahr']. '/'; $link = $domain . '/dresses/' . $_POST['jahr'] . '/'. $file_name; $name_insert = mysql_real_escape_string($_POST['name']); $brand_insert = mysql_real_escape_string($_POST['brand']); $style_insert = mysql_real_escape_string($_POST['style']); $jahr_insert = mysql_real_escape_string($_POST['jahr']); $desc_insert = mysql_real_escape_string($_POST['desc']); mysql_query("SET CHARACTER SET 'utf8'"); $sql_upload="INSERT into dresses (model,brand,style,jahr,beschreibung) VALUES('$name_insert','$brand_insert','$style_insert','$jahr_insert','$desc_insert')"; $result = mysql_query($sql_upload,$db); $dress_id = mysql_insert_id(); $sql_image = "Insert into images (dress_id, url) VALUES ('$dress_id','$link')"; $result = mysql_query($sql_image, $db); $desired_dir= $url; if(empty($errors)==true){ if(is_dir($desired_dir)==false){ mkdir("$desired_dir", 0755, true); // Create directory if it does not exist } if(is_dir("$desired_dir/".$file_name)==false){ move_uploaded_file($file_tmp,"$desired_dir/".$file_name); $source_img = "$desired_dir/".$file_name; $destination_img = $desired_dir."/".$file_name; $d = compress($source_img, $destination_img, 50); }else{ // rename the file if another one exist $new_dir="$desired_dir/".$file_name.time(); rename($file_tmp,$new_dir) ; } </code></pre> </div>


文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...


软件测试2小时入门,让您快速了解软件测试基本知识,有系统的了解; SQL一小时,让您快速理解和掌握SQL基本语法 jmeter性能测试 ,让您快速了解主流来源性能测试工具jmeter 测试管理工具-禅道,让您快速学会禅道的使用,学会测试项目、用例、缺陷的管理、


基于西门子S7—1200的单部六层电梯设计程序,1部6层电梯。 本系统控制六层电梯, 采用集选控制方式。 为了完成设定的控制任务, 主要根据电梯输入/输出点数确定PLC 的机型。 根据电梯控制的要求,




深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

图书管理系统(Java + Mysql)我的第一个完全自己做的实训项目

图书管理系统 Java + MySQL 完整实训代码,MVC三层架构组织,包含所有用到的图片资源以及数据库文件,大三上学期实训,注释很详细,按照阿里巴巴Java编程规范编写


人工智能、物联网、大数据时代,Linux正有着一统天下的趋势,几乎每个程序员岗位,都要求掌握Linux。本课程零基础也能轻松入门。 本课程以简洁易懂的语言手把手教你系统掌握日常所需的Linux知识,每个知识点都会配合案例实战让你融汇贯通。课程通俗易懂,简洁流畅,适合0基础以及对Linux掌握不熟练的人学习; 【限时福利】 1)购课后按提示添加小助手,进答疑群,还可获得价值300元的编程大礼包! 2)本月购买此套餐加入老师答疑交流群,可参加老师的免费分享活动,学习最新技术项目经验。 --------------------------------------------------------------- 29元=掌握Linux必修知识+社群答疑+讲师社群分享会+700元编程礼包。 &nbsp;


本课程适合CCNA或HCNA网络小白同志,高手请绕道,可以直接学习进价课程。通过本预科课程的学习,为学习网络工程师、思科CCNA、华为HCNA这些认证打下坚实的基础! 重要!思科认证2020年2月24日起,已启用新版认证和考试,包括题库都会更新,由于疫情原因,请关注官网和本地考点信息。题库网络上很容易下载到。


C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

微信小程序 实例汇总 完整项目源代码

微信小程序 实例汇总 完整项目源代码


&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。




限时福利1:购课进答疑群专享柳峰(刘运强)老师答疑服务 限时福利2:购课后添加学习助手(微信号:csdn590),按消息提示即可领取编程大礼包! 为什么说每一个程序员都应该学习MySQL? 根据《2019-2020年中国开发者调查报告》显示,超83%的开发者都在使用MySQL数据库。 使用量大同时,掌握MySQL早已是运维、DBA的必备技能,甚至部分IT开发岗位也要求对数据库使用和原理有深入的了解和掌握。 学习编程,你可能会犹豫选择 C++ 还是 Java;入门数据科学,你可能会纠结于选择 Python 还是 R;但无论如何, MySQL 都是 IT 从业人员不可或缺的技能! 【课程设计】 在本课程中,刘运强老师会结合自己十多年来对MySQL的心得体会,通过课程给你分享一条高效的MySQL入门捷径,让学员少走弯路,彻底搞懂MySQL。 本课程包含3大模块:&nbsp; 一、基础篇: 主要以最新的MySQL8.0安装为例帮助学员解决安装与配置MySQL的问题,并对MySQL8.0的新特性做一定介绍,为后续的课程展开做好环境部署。 二、SQL语言篇: 本篇主要讲解SQL语言的四大部分数据查询语言DQL,数据操纵语言DML,数据定义语言DDL,数据控制语言DCL,学会熟练对库表进行增删改查等必备技能。 三、MySQL进阶篇: 本篇可以帮助学员更加高效的管理线上的MySQL数据库;具备MySQL的日常运维能力,语句调优、备份恢复等思路。 &nbsp;

navicat简体中文版 绿色版 (64位)







文章目录经典飞机大战一.游戏设定二.我方飞机三.敌方飞机四.发射子弹五.发放补给包六.主模块 经典飞机大战 源代码以及素材资料(图片,音频)可从下面的github中下载: 飞机大战源代码以及素材资料github项目地址链接 ————————————————————————————————————————————————————————— 不知道大家有没有打过飞机,喜不喜欢打飞机。当我第一次接触这个东西的时候,我的内心是被震撼到的。第一次接触打飞机的时候作者本人是身心愉悦的,因为周边的朋友都在打飞机, 每

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

Qt5.10 GUI完全参考手册(强烈推荐)





课程亮点: 课程培训详细的笔记以及实例代码,让学员开始掌握设计模式知识点 课程内容: 工厂模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式、原型模型、代理模式、单例模式、适配器模式 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式 课程特色: 笔记设计模式,用笔记串连所有知识点,让学员从一点一滴积累,学习过程无压力 笔记标题采用关键字标识法,帮助学员更加容易记住知识点 笔记以超链接形式让知识点关联起来,形式知识体系 采用先概念后实例再应用方式,知识点深入浅出 提供授课内容笔记作为课后复习以及工作备查工具 部分图表(电脑PC端查看):

进程监控软件 Performance Monitor中文版






2019 Python开发者日-培训



一 专题从基础的C语言核心到c++ 和stl完成基础强化; 二 再到数据结构,设计模式完成专业计算机技能强化; 三 通过跨平台网络编程,linux编程,qt界面编程,mfc编程,windows编程,c++与lua联合编程来完成应用强化 四 最后通过基于ffmpeg的音视频播放器,直播推流,屏幕录像,




机器学习实战系列套餐以实战为出发点,帮助同学们快速掌握机器学习领域必备经典算法原理并结合Python工具包进行实战应用。建议学习顺序:1.Python必备工具包:掌握实战工具 2.机器学习算法与实战应用:数学原理与应用方法都是必备技能 3.数据挖掘实战:通过真实数据集进行项目实战。按照下列课程顺序学习即可! 课程风格通俗易懂,用最接地气的方式带领大家轻松进军机器学习!提供所有课程代码,PPT与实战数据,有任何问题欢迎随时与我讨论。


原价169,限时立减100元! 系统掌握Python核心语法16点,轻松应对工作中80%以上的Python使用场景! 69元=72讲+源码+社群答疑+讲师社群分享会&nbsp; 【哪些人适合学习这门课程?】 1)大学生,平时只学习了Python理论,并未接触Python实战问题; 2)对Python实用技能掌握薄弱的人,自动化、爬虫、数据分析能让你快速提高工作效率; 3)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; 4)想修炼更好的编程内功,优秀的工程师肯定不能只会一门语言,Python语言功能强大、使用高效、简单易学。 【超实用技能】 从零开始 自动生成工作周报 职场升级 豆瓣电影数据爬取 实用案例 奥运冠军数据分析 自动化办公:通过Python自动化分析Excel数据并自动操作Word文档,最终获得一份基于Excel表格的数据分析报告。 豆瓣电影爬虫:通过Python自动爬取豆瓣电影信息并将电影图片保存到本地。 奥运会数据分析实战 简介:通过Python分析120年间奥运会的数据,从不同角度入手分析,从而得出一些有趣的结论。 【超人气老师】 二两 中国人工智能协会高级会员 生成对抗神经网络研究者 《深入浅出生成对抗网络:原理剖析与TensorFlow实现》一书作者 阿里云大学云学院导师 前大型游戏公司后端工程师 【超丰富实用案例】 0)图片背景去除案例 1)自动生成工作周报案例 2)豆瓣电影数据爬取案例 3)奥运会数据分析案例 4)自动处理邮件案例 5)github信息爬取/更新提醒案例 6)B站百大UP信息爬取与分析案例 7)构建自己的论文网站案例

相关热词 c#分级显示数据 c# 不区分大小写替换 c#中调用就java c#正则表达式 验证小数 c# vscode 配置 c#三维数组能存多少数据 c# 新建excel c#多个文本框 c#怎么创建tcp通讯 c# mvc 电子病例