PHP - Mysqli Query In A Loop Takes Longer With Each Iteration. Why?
$start = 0;
Similar TutorialsTo solve a bigger issue I'm having in WordPress, I have thrown together this basic script in PHP script to help me get to the bottom of it. Basically, I am trying to add a <hr /> tag after every 3rd paragraph: http://www.mattpealing-server.co.uk/~freshmat/wp-content/themes/match2move/test.php With the following code: <?php $count = 0; ?><?php while($count < 20) : ?><span><p><strong><?php echo $count; ?>:</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p></span><?php if ($count % 3) : ?><hr /><?php endif; ?><?php $count ++; ?><?php endwhile; ?>() However if you notice, this output just doesn't turn out like this! Does the operator I'm using not test if $count is a multiple of 3? So I have a very simple for loop that I am populating a list with levels and exp required to achieve the next level. I have been using a sandbox to test my output and have also created an excel sheet to replicate the data to verify the content. This code was not mine from the beginning and in creating the spreadsheet I discovered the flaw. Below is the code I am trying to fix: function experience($L, $pres = 0) { $a = 0; $end = 0; for ($x = 1; $x < $L; ++$x) { $a += $x * round($x + 5 * pow(4, ($x / 300))); } if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } if ($x > 399) { $a += $x * round($x + 11 * pow(4, ($x / 280))); } if ($x > 599) { $a += $x * round($x + 19 * pow(4, ($x / 270))); } if ($x > 799) { $a += $x * round($x + 35 * pow(4, ($x / 260))); } if ($x > 999) { $a += $x * round($x + 67 * pow(4, ($x / 250))); } return round($a / 1.25); } Below is the troubleshooting I am attempting to do (Modified and simplified for and while loop): //for loop $no = 200; $a = 0; for ($x = 1; $x < $no; ++$x) { $a += $x + 1; } if ($no > 199) { $a += $x + 2; } echo $a; //while loop $no = 200; $a = 0; $x = 1; while (($x - 1) < $no) { $a += $x * round($x + 5 * pow(4, ($x / 300))); $x++; if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } } echo $a; Upon request I can also provide snipets of the excel sheet. So the gist of what the issue I am having is this. Between level 199 and 200 the iteration of the loop is running one extra time through the initial formula. As you can tell at level 200, 400, 600, 800 and 1000 I want this formula to change so that it simplifies the amount of exp required to achieve the next level. I can not for the life of me figure out how to restrict the loop while still allowing the values 200 up to run through it for the first 199 iterations. The output I should get from the primary code for levels 199 through 201 are as follows: 199 = 200 = 201 = At level 199 I am good but for whatever reason it runs one additional iteration at the level 1-199 formula and then moves on to the 200 level formula messing up the values. Any and all help is much appreciated. I am a novice hobbyist at best and have been doing this for many, many years now but sometimes I get stumped. I chalk it up to lack of proper training and time to really be serious with it. Thanks in advance....NICON I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#! Hello,
Got a code, need to insert a query for displaying links of posts in section. Category is 'blog', each post has it's 'id', and 'subject', which should be a name for link, such as "blog.php?p='id'".
<!doctype html> <html lang="en"> <head> </head> <body class="base"> <div class="container"> <!-- PRZETWARZANIE WYNIKÓW Z BAZY --> <?php $total_pages = $link->query('SELECT * FROM news WHERE category="blog"')->num_rows; $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1; $num_results_on_page = 1; if ($stmt = $link->prepare('SELECT * FROM news WHERE category="blog" ORDER BY date DESC LIMIT ?,?')) { $calc_page = ($page - 1) * $num_results_on_page; $stmt->bind_param('ii', $calc_page, $num_results_on_page); $stmt->execute(); $result = $stmt->get_result(); } while ($row = $result->fetch_assoc()): $text = $row['news']; $text = str_replace('[video]','<div class="video-container">',$text); $text = str_replace('[/video]','</div>',$text); $text = str_replace('[media]','',$text); $text = str_replace('[/media]','',$text); $embera = new \Embera\Embera(); echo '<div class="container"> <div class="row">'; ?> <div class="col-sm-4"> /* here is a place for links to published posts */ </div> <?php echo '<div class="col-sm-8"><h3>'.$row['subject'].'</h3>'; echo '<div class="tresc embed-responsive">'; echo $embera->autoEmbed($text); echo '</div></div> </div> </div>'; endwhile; ?> <!-- KONIEC PRZETWARZANIA WYNIKÓW Z BAZY --> <hr class="pagination_divider"> <center> <!-- PAGINATION --> <?php if (ceil($total_pages / $num_results_on_page) > 0): ?> <div class="sect_paginate"><ul class="pagination"> <?php if ($page > 1): ?> <li class="prev"><a href="blog.php?page=<?php echo $page-1 ?>">◂ WSTECZ</a></li> <?php endif; ?> <li class="currentpage"><a href="blog.php?page=<?php echo $page ?>"><?php echo $page ?></a></li> <?php if ($page < ceil($total_pages / $num_results_on_page)): ?> <li class="next"><a href="blog.php?page=<?php echo $page+1 ?>">DALEJ ▸</a></li> <?php endif; ?> </ul></div> <?php endif; $stmt->close(); ?> </center> <!-- END OF PAGINATION --> </div> </body> </html>
Hi, I am having problems returning values from a select statement. When I query directly in the databse, I get back the information I am looking for. I use an includes file for the database connection and my page shows that the connection was successful. Here is my code: Code: [Select] <?php $search = $_GET['searchFor']; $words = explode(" ", $search); $phrase = implode("%' AND articlename LIKE '%", $words); $sql ="SELECT * FROM articles WHERE articlename LIKE '%phrase%'"; $result =$conn->query($sql) or die('Sorry, could not get any articles at this time'); $row =($result->fetch_all()) or die('No records found'); $numRows =$result->num_rows; If($numRows==0) { echo "<h2>Sorry, no articles were found with '$search' in them.</h2>"; } else { While($row=$result->fetch_assoc()) { $articleid = $row['articleid']; $title = $row['articlename']; $shortdesc = $row['shortdesc']; echo "<h2>Search Results</h2><br><br>\n"; echo "<a href=\"index.php?content=showarticle&id=$articleid\">$title</a><br>\n"; echo "$shortdesc<br><br>\n"; } } ?> The search term is coming from a search form in the navigation. I have used "echo" statements to check and make sure that the sesrch word is coming through to tghe page containing the above code. I have tried mysqli_error() statements in several places and don't see where the problem is. When I try the search the message that comes back is "No records found" Does not makee sense because I know it is there, can find it, and even have the same syntax as the SELECT statement I use when I ask for the php code. Going crazy trying to sort this out. Any suggestions, help etc are greatly appreciated. Thank youi. Hello guys, i'm currently building my own cms, a personal project, and now im stucked on an error "Call to a member function query() on a non-object in.. please help
after creating this function.. I know the db connection and everything else worked out because i have a similar function that works just without the switch or the numrow if statement.
protected function _pageStatus($option, $id){ //check if page exists, if it does return the status, or return 404 switch($option){ case 'alpha' : $sql = "SELECT status FROM pages WHERE nick = '$id'"; break; case 'num' : $sql = "SELECT status FROM pages WHERE id = '$id'"; break; } if($result = $this->_db->query($sql)){ //<--- THE ERROR WAS ON THIS LINE. if($result->num_rows > 0){ while ($status = $result->fetch_object()) { return $status; } return $status; $result->close(); } else { return 404; } } } Hi,
So I'm not very familiar with using mySQLi, but I'm wanting to print a user's last name, depending on which user is logged in (obviously it needs to be their last name and not another users)
So, we're getting the session for the user and saving their username as $username
$user = Session::Get('current_user'); $username = $user->Get('username');And then my query to display their lastname? $result = $db->Select('lastname')->Where('username', '$username')->Get(Config::Get('db.table')); print_r($result)But the query doesn't work, no error? Forgive my ignorance! >.< I have a function that performs a SELECT query on a MySQL database and populates the results in an array of Class. At the moment it is using PDO. Trouble is that PDO is not supported by the server the code will run on. Changing server is not an option, nor is installing PDO.
I have tried splitting the function to use the PDO method if installed or MySQLi if not. I am struggling to get the MySQLi part working though. Can anyone help me with this?
Here is the function I have so far which basically returns nothing from the MySQLi part:
public function mysqlSelectToClass($query, $className, $args = NULL) { include (dirname(__FILE__) . "/../config.php"); if (class_exists('PDO')) { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbQuery = $db->prepare($query); if (isset($args)) { foreach ($args as $arg) { $dbQuery->bindParam(array_values($arg)[0], array_values($arg)[0], PDO::PARAM_STR); } } $dbQuery->execute(); return $dbQuery->fetchAll(PDO::FETCH_CLASS, $className); } else { $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name); $dbQuery = $db->prepare($query); if (isset($args)) { // Type is a string of parameter types e.g. "is" $type = array_values($args)[0]; // Params is an array of parameters e.g. array(1, 'value') $params = array_values($args)[1]; call_user_func_array('mysqli_stmt_bind_param', array_merge(array($dbQuery, $type), $this->byrefValues($params))); $result = mysqli_stmt_execute($dbQuery); mysqli_close($db); } elseif ($dbResult = mysqli_query($db, $query)) { $result = mysqli_fetch_object($dbResult, $className); mysqli_close($db); } return $result; } }the byrefValues function is simply swapping a value array to a reference array and seems to be working fine. I can paste that too if required. Thanks Jay Edited by jay20aiii, 24 September 2014 - 12:41 PM. Hi,
I can I include a date range criteria to query with in the following code? The date field in the table (t_persons) is IncidentDate.
$criteria = array('FamilyName', 'FirstName', 'OtherNames', 'NRCNo', 'PassportNo', 'Gender', 'IncidenceCountryID', 'Status', 'OffenceKeyword', 'AgencyID', 'CountryID', 'IncidenceCountryID' ); $likes = ""; $url_criteria = ''; foreach ( $criteria AS $criterion ) { if ( ! empty($_POST[$criterion]) ) { $value = ($_POST[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]); } elseif ( ! empty($_GET[$criterion]) ) { $value = mysql_real_escape_string($_GET[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]); } //var_dump($likes); } $sql = "SELECT * FROM t_persons WHERE PersonID>0" . $likes . " ORDER BY PersonID DESC";Kind regards. Hello everyone! I am trying to insert a student into a table (with TIMESTAMP; works with VARCHAR, not TIMESTAMP). Can anyone help?
Variable
$time_stamp = date("D M j G:i:s T Y");Populate DB Query ("DROP TABLE IF EXISTS enrolled") || !$link->query("CREATE TABLE enrolled(course_id VARCHAR(50), student_id VARCHAR(50), user_ip VARCHAR(50), time_stamp TIMESTAMP(6))Insert Query INSERT INTO enrolled(course_id,student_id,user_ip,time_stamp) VALUES('$course','$number','$user_ip','$time_stamp') Edited by MatthewPatten, 12 December 2014 - 08:32 AM. Hello there, I'm new to this site/forum so i dont know if this is the right forum to post a code review / commentary request .... I have a function that handels the sql code... Know i would like to know what you think off it ? can I do something different or better ?.. Code: [Select] <?PHP /* * Private function db_query($sql) | handle.... * whit checking en extendid error reporting.... * Runs a query but does not return a result array.... * @String $sql | this is the sql query you whant to run..... */ private function db_query($sql) { $this->sql = $sql; switch ( DEBUG_QUERY ) { // check debug mode... case true: try { // probeer query uit te voeren... $handle = $this->query($this->sql); if(!$handle) // if error whit the query... { $this->rollback(); throw new Exception('MySQLi Query went wrong error ==> ' . mysqli::$error); } } catch (Exception $e) { // error afhandeling and reporting.. echo '<hr />'; echo '<span style="color:red"><b>A MySQLi Query went wrong:</b></span><br />'; echo var_dump($e->getMessage()); echo '<br />'; echo nl2br($e->getTraceAsString()); echo '<br />'; echo 'Error in File: ' . $e->getFile(); echo '<br />'; echo 'Thrown Exception on line: ' . $e->getLine(); echo '<br /><hr />'; exit(); } // end error afhandeling and reporting... break; case false: $handle = $this->query($this->sql); break; } // end switch... return $handle; } /* * Public function db_Do | handels the insert, update, select and delete query's * A lot off optional options for the different query's * @String $type | Choose between the four type's | select, insert, update or delete | Default is Select * @String $table | Select witch table you whant to use | give a vailid tablename you whant to use in the query * @String $values | Input the values uw whant to select from the table | * for all - row1, row2, row3 | id, username, password * @String $where | The where operator for the query | Where $where = | give a vailid row name | if used you must fill in the other two where operators | default = empty (optional) * @String $opparator | The operator for the where operator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | where 2 | default = empty (optional) * @String / Int $where_val | The where value for the where operator | WHERE $where{id} $opparator{=} $where_val{1} | where 3 | default = empty (optional) * @Bool $use_and | if TRUE you can use the AND operator | linked to the other three and operators | if you use 1 you must fill in all 4 of them | default = false (optional) * @String $and_key | Value for the AND operator | same as $order_by | AND $and_key{username} | and 2 | default = empty (optional) * @String $and_oparetor | The operator for the and section | same as $opparator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | and 3 | default = '=' (optional) * @String $and_value | The value for by the and_key | same as $where_val | AND $and_key{username} $and_oparetor{=} $and_value{'jhon'} | and 4 | default = empty (optional) * @String $order_by | value for the Order by operator only used if hase a value | ORDER BY $order_by{id} | if used you must alsow fill in the second order by operator | default = empty (optional) * @String $order_key | Value for the Order key by the order value | ORDER BY $order_by{id} $order_key{asc, desc} | check in_array | default = asc (optional) * Error msg and checks includid, Failsafe... * Runs the query and returns a row.... * Uses the db_query function... * Version 1.0.0 */ public function db_Do($type = 'select', $table, $values, $where = NULL, $opparator = NULL, $where_val = NULL, $use_and = FALSE, $and_key = NULL, $and_oparetor = '=', $and_value = NULL, $order_by = NULL, $order_key = 'ASC') { switch ( DEBUG_QUERY ) { // check debug mode... case true: if(in_array($type, $this->SQL_TYPE, TRUE)) { // check for correct $type... if(in_array($order_key, $this->ORDER_KEY, TRUE)) { // check if order key is allowd $order_key.... if(in_array($opparator, $this->OPARATORS, TRUE)) { // check for vallid oparetors... if(empty($table) or strlen($table) >= 4) { // check if $table correct is.... if(empty($values) or strlen($values) >= 4) { // check if the $values are given correctly.... if(in_array($and_oparetor, $this->OPARATORS, TRUE)) { // check if and oparetor is allowd..... switch( $type ) { // witch type... case 'select': // Build the SQL Query.... $query = 'SELECT '. $this->real_escape_string($values) .' FROM '. $table .' '; if(!empty($where) and (empty($where_val) or empty($opparator))) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } elseif(!empty($where) || !empty($where_val) || !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } if(!empty($order_by)) { $query .= ' ORDER BY '. $order_by .' '. $order_key .''; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = $handle->fetch_assoc(); mysqli_free_result($handle); break; case 'insert': // Build the SQL Query...... $query = 'INSERT INTO '. $table .' ('. $this->real_escape_string($values) .') '; $query .= 'VALUES ('. $this->real_escape_string($where) .')'; $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle... break; case 'update': // Build the SQL Query...... $query = 'UPDATE '. $table .' '; $query .= 'SET '. $this->real_escape_string($values) .' '; if(!empty($where) and !empty($where_val) and !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } elseif(empty($where) or empty($where_val) or empty($opparator)) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; case 'delete': //Construct the delete query..... $query = 'DELETE FROM '. $table .' '; $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; } // end switch( $type )..... } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the AND section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // Correct VALUES..... $row = 'Sorry you have to fill in the values parameter correctly and it hase to be bigger then 3 chars.'; } } else { // Correct TABLE.... $row = 'Sorry you have to fill in the table parameter correctly and it hase to be bigger than 3 chars.'; } } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the WHERE section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // if order_key is NOT allowd.... $row = 'Incorrect Order by opparator: <b>'. $order_key .'</b> choos between (asc or desc)'; } } else { // if not correct type return error msg.... $row = 'Incorrect type: <b>'. $type . '</b> choose between (select, insert, update or delete)'; } break; // end case true... case false: break; // end case false... } // end switch( debug_query )... return $row; } // end public function db_Do()..... ?> It's still a work in process so it's not done yet... Hi ! I am trying to translate my mysqli count query that works perfectly into prepared statements. Unfortunately, after playing around and using my knowledge of PS, I have come up with this script which fails to execute and returns a http 500 error. I may have missed something very silly, I require some guidance on fixing the error.
<?php $conn = mysqli_connect("xxxx", "xxxx", "xxxx", "xxx"); $sel_query = "SELECT S1, B1 COUNT(IF(S1 = ?, 1, NULL)) 'Accepted', COUNT(IF(S1 = ?, 1, NULL)) 'Rejected', COUNT(IF(S1 = ?, 1, NULL)) 'Under_Review' FROM Enrol"; $stmt = $conn->prepare($sel_query); $Accepted="Accepted"; $Rejected="Rejected"; $Under_Review="Under Review"; $stmt->bind_param("sss",$Accepted, $Rejected, $Under_Review); $stmt->execute(); $result = $stmt->get_result(); // get the mysqli result if($result->num_rows === 0) exit('No records found!'); while($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row["Accepted"]; ?></td> <td><?php echo $row["Rejected"]; ?></td> <td><?php echo $row["Under_Review"]; ?></td> </tr> </table>
Edited June 24, 2020 by PythonHelp Hi Could do with some help. I have 20 clients (client-1, client-2, client-3) and so on. Each client makes several calls per day. How can I get a row count from two columns (Date, clid) and echo the count for each client? What I am trying to do is query a database using a loop conditional and return the data but my code only repeats the first instance multiple times! My code is below, I have tried to use comments to explain what should be happeing! $rows = null; $q1 = "SELECT * FROM table"; $r1 = mysql_query($q1) or die(mysql_error()); $i = 1; while($i <= 5){ $start = (1000 * $i); $end = ($start + 1000); while($a1 = mysql_fetch_array($r1, MYSQL_ASSOC)){ /* query the database where 'start' is >= 1000 and where 'end' is <= 2000, this should loop so the next time is where 'start' >= 1000 * $i should be 1000 then 2000, 3000 etc... and where 'end' should be 2000, 3000, 4000 etc... */ if($a1['start'] >= $start && $a1['end'] <= $end){ $rows .= $a1['col1'].':'.$a1['col2']."\n"; } } echo nl2br(trim($rows.'<p>')); $i++; } /* The problem is that it always shows multiple instances of the first result only where start = 1000 and end = 2000 */ Any help would be much appreciated!! I am in the process of making a stream page where users can enter a status, like and comment others statuses, like on facebook.
I have 4 tables, stream, users, likes and comments as shown below, with the rows I will be using:
stream stream_status This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306079.0 So I output the Threads for my forum onto the main screen like so <div class ='grid-container'> <?php //Get the Threads and output them onto the screen in a grid container $query = mysqli_query($conn, "SELECT * FROM Threads order by id desc") or die (mysqli_error($conn)); $GetPostsQuery = mysqli_query($conn, "SELECT Count(*) FROM Posts") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { $imageURL = 'upload/Thumbnails/'.rawurlencode($row["filename"]); $PostBody = nl2br($row['ThreadBody']); echo " <div class ='grid-item'> <div class='ThreadComment'> Comments: <br> </div> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <h2><a href='viewthread.php?id={$row['id']}'> {$row['Title']} </a></h2> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <p>$PostBody </p> </div> \n"; } ?> However I don't keep the count of comments against the threads on my Threads table. I've attached a "describe" of both my comments (named Posts) and my Threads table (name Threads) I want to output the count of the comments against each Post in the above While loop To obtain the amount of comments against a thread I can get this from SQL by doing select count(IdOfThread) from Posts where id='169' ; But how would I access a query in SQL for the Posts table whilst it's already querying the Threads table? How would I implement this into the above while loop? Many thanks (and my db design maybe incorrect I'm very new )
Basically, this part of the code is checking the "scanned" table in my mysql database to get the last scanned date for the item at hand. It then takes that date and selects all the vendor items in the odbc table "ARVEND" that are greater than the last purchase date. || This is where I am running into a problem. When it loops through each vendor item it selects from the "associated" mysql table to see if the vendor item has been scanned. If it does not find anything I am trying to get the $checkpurdate variable to add 1 to itself. | In the second script you will see the elseif($checkpurdate>0) .... Here I am saying if there are any vendor items that have not been scanned, highlight the row in yellow. But, this part of my code $checkpurdate = $checkpurdate + 1; does not seem to be counting correctly. Sometimes it counts '4' for an item when there are only two vendor items available. All of this may sound confusing since you may not know what I am trying to do. But, the main problem I am having is the counting part is returning wrong numbers. $checkpurdate = $checkpurdate + 1; Code: [Select] /* $checkpurdate */ $query3 = "SELECT date FROM scanned WHERE `item` = '$ITEM' ORDER BY date DESC LIMIT 1"; $result3 = mysql_query($query3); $checklastdate = ""; while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {$checklastdate= $row3['date']; $checklastdate=date("m/d/y", strtotime($checklastdate)); } //checkpurdate loops $checkassoc="0"; $checkpurdate="0"; $sqlc="SELECT RECNO5 FROM ARVEND WHERE PURDATE1 > '$checklastdate' AND ITEM = '$ITEM'"; $rsc=odbc_exec($conn,$sqlc); if (!$rsc) {exit("Error in SQL");} while (odbc_fetch_row($rsc)) { $checkrecno5=odbc_result($rsc,"RECNO5"); $checkassosquery = "associated WHERE `VENDORID` = '$checkrecno5' AND ITEM = '$ITEM'"; $checkassoc = get_rows($checkassosquery); if($checkassoc>0) { // do nothing } else { $checkpurdate = $checkpurdate + 1; } } Code: [Select] elseif($checkpurdate>0) { echo"<TR class=\"NV\"> <TD>"; } Hi, Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have: $query1="SELECT UserID FROM Users where RefID='$userid'"; $result1=mysql_query($query1); while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5') { echo ($row[0]); echo " "; $sql2 = "SELECT * FROM Users WHERE RefID=$row[0]"; $sql2result = mysql_query($sql2); $sql2querynum = mysql_numrows($sql2result); } Problem is, for every value it echoes out, I get the following warning: mysql_numrows(): supplied argument is not a valid MySQL result resource Like I said, I'm a newbie to PHP to maybe I'm not even going about doing this the right way. Hoping someone can help to point me in the right direction. |