PHP - While Loop Returns Null
Hi, I am trying to expand my very limited PHP by building a CMS. It's all new to me so please be courteous with your replies ? I little history of my problem. I am running xampp on a windows 10 running php 5.6.38
I have taken two video courses and on each I got stumped halfway through with a very similar problem. I am copying everything word for word and even downloaded the course file on the first one and still got the same problem so I'm wondering if there is something wrong with my setup - config?.
The problem.
This is the code: <?php error_reporting(E_ALL); ini_set('display_errors',1); include("includes/database.php"); include("includes/header.php"); if ($connection) { echo "Great, we're connected to the database<br><br>"; }else { echo "Bummer, it didn't connect to the database!"; } $query = "SELECT * FROM categories"; $result_set = mysqli_query($connection, $query) ; if (!$result_set) { die("Query Failed".msqli_error($connection)); } while ($row = mysqli_fetch_array($result_set)) { echo $row['cat_title']; } var_dump($result_set); ?>
Great, we're connected to the database object(mysqli_result)#3 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }
Question:
Thanks for your help. Similar TutorialsHey guys tried to search for this but didn't find anything usefull about the issue. So what i have is mssql_fetch_array in a while loop in the loop i have it assign a specified row as a variable that i can print later on in the page. Code: [Select] while($row = mssql_fetch_array($query) { $tables = "<tr>"; $tables .= "<td> {$row['specifiedrow']} </td>"; $tables .= "</tr>"; }Then i call it in the html table as Code: [Select] <? php echo $tables; ?> I have done this with mysql_fetch_array before and it would print the entire database row associated with that row in the table. But as it is now it only returns the last row from the database. Is there something i am missing. Thanks for any help I have a for loop that I am looping through. When I use var_dump() I get 10 results (which is what I should be getting). However, when I loop through it using a for() loop I am getting an extra 11th value that is blank. What would be causing this? My code is below: Code: [Select] $legacy = new Legacy(); // Loop through each film in the shopping cart for ($i = 0; $i < $myShoppingCartInfo['row_count']; $i++) { // Determine if the film is of a legacy series if ($legacy->isLegacyCheckout($myShoppingCartInfo['data']['PRODUCTSKUID'][$i])) { // Declare array to hold all legacy film entity_id values $legacyEntityIds = array(); $legacyEntityIds = $legacy->getLegacyEntityIds($myShoppingCartInfo['data']['PRODUCTSKUID'][$i]); var_dump($legacyEntityIds); // Loop through all legacy video entity_id's for ($i = 0; $i < $legacyEntityIds['data']['ENTITY_ID']; $i++) { // Grant streaming access to each entity id echo $legacyEntityIds['data']['ENTITY_ID'][$i] . '<br />'; // Insert the product into the order items table /*$query = "INSERT INTO tblOrderItems (OrderItemID, ProductSKUID, RentalDate, OrderID) VALUES (##newID##, '".$myShoppingCartInfo['data']['PRODUCTSKUID'][$i]."', ".($myShoppingCartInfo['data']['RENTALDATE'][$i] === NULL ? 'NULL' : "'".$myShoppingCartInfo['data']['RENTALDATE'][$i]."'").", ".$newOrderID.")"; $cartItemInserted = counter_id_insert($query,'OrderItemID'); $curr_user->addNewEntityLicense($legacyEntityIds['data']['ENTITY_ID'][$i]);*/ } } When I view the source code of the output page in a browser, this is what I see: array(5) { ["row_count"]=> int(10) ["col_count"]=> int(1) ["col_names"]=> array(1) { => string(9) "entity_id" } ["col_types"]=> array(1) { => string(3) "int" } ["data"]=> array(1) { ["ENTITY_ID"]=> array(10) { => string(7) "1681799" [1]=> string(7) "1681872" [2]=> string(7) "1681871" [3]=> string(7) "1681870" [4]=> string(7) "1681869" [5]=> string(7) "1681868" [6]=> string(7) "1681867" [7]=> string(7) "1681866" [8]=> string(7) "1681865" [9]=> string(7) "1681864" } } } 1681799<br />1681872<br />1681871<br />1681870<br />1681869<br />1681868<br />1681867<br />1681866<br />1681865<br />1681864<br /><br /> in my code below the **data is extracted correctly for the first foreach but doesn't return anything for 2nd foreach though selected one present inside the 2nd foreach** i still get the error Warning: Invalid argument supplied for foreach() for line `foreach ($authorlist as $post)`... however the 2nd foreach returns data correctly as soon as i remove the first foreach loop. I am trying to update the database with isset to set the value of the variable to either null or the value entered by the user. Currently, if no value has been entered null is being set as a string causing the date field to populate with zeros. How do I code it so that it populates or sets the value as null and not as string null?
Here's my code: (yes I know sql injections it's still in development )
<?php Hey.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? Hello, i have a query that returns the rows of certain parts of a databse. i made a button on the end of each echo, to make sure that, the button being printed with each echo, correlates to that echo. However, the SESSIONS only return the same varaibles each time. The last in the list. $sql = "SELECT p.Title, p.PerfDate, p.PerfTime FROM performance AS p INNER JOIN production AS r ON p.Title = r.Title"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo '<tr> <td>'.$row['Title'].'</td> <td>'.$row['PerfDate'].'</td> <td>'.$row['PerfTime'].'</td> <td><button name="availability" value="'.$row['Title'].'">Availability</button></td> </tr>'; $_SESSION["Title"] = $row['Title']; $_SESSION["PerfDate"] = $row['PerfDate']; $_SESSION["PerfTime"] = $row['PerfTime']; } } else { echo "0 results"; } $_SESSION["name"] = $_GET["name"]; ?> How am i able to make it so each button correlates to each row?
There's a screenshot of how it looks for reference Edited December 8, 2019 by AdamSteele this is supposed to display the distinct first two characters of a string(billnmbr) in a combobox ive tried this on phpmyadmin and it returns 08.. which is correct when i run this on my server, it returns nothing.. there must be something wrong with the way i called the billnmbr does anybody have an idea on how i could call and display this correctly? thanks and have a nice day. <?php $mquery = "select distinct(substring(`billnmbr`, 1, 2)) from `tbltest`"; $mres =mysql_query($mquery) or die(mysql_error()); while($mrow=mysql_fetch_array($mres)){ $mm = $mrow['billnmbr']; echo "<option value=" . $mrow['billnmbr'] . ">"; echo $mrow['billnmbr'] . "</option>"; } echo " </select>"; ?> im not new enough for this to take so long to figure out, but for some reason $rs = mysql_query("SELECT * FROM cl"); returns the last record instead of all the records in the table. anyone know why it wouldnt take everything? I'm getting frusted over an if else statememt that won't work. It is calling one variable from the table. If the variable is in the table it will display one thing, if the variable is absent, it should display something else. I've tried !empty, isset, even $num_rows =1, but the content in the else doesn't display. Here's the code: Code: [Select] <? $result = mysql_query( "SELECT * FROM codeWords WHERE Mycode = '$MyCode' " ) or die("SELECT Error: ".mysql_error()); $num_rows = mysql_num_rows($result); while ($row = mysql_fetch_array($result)) { extract($row); if (!empty( $MyCode )) { echo "here is the code word"; } else { echo "you need to go back and get the code"; } $row_count++; } mysql_close; ?> When the code variable is correct the "here is the code word" displays. when the code variable is incorrect, what should appear as "you need to go back and get the code" is just blank. Any thoughts on how to structure the query in such a way that eh incorrect text appears? Thanks, I'm hoping someone can help me cos my hair's going white with this one. I'm trying to put together a script that acts as web-based interface to an SQL server. There are actually two parts, admin.htm and admin.php. The first part is just a form that passes login credentials to the PHP file. That part seems to work fine, but I'll post the source anyway: - Code: [Select] <!DOCTYPE HTML> <html lang="en"> <head> <title>SQL admin login</title> <meta charset="iso-8859-1" /> </head> <body> <form action="admin.php" method="post"> <label for="username">Username: -</label> <br /> <input type="text" name="username" id="username" /> <br /> <br /> <label for="password">Password: -</label> <br /> <input type="password" name="password" id="password" /> <br /> <br /> <label for="server">Server: -</label> <br /> <input type="text" name="server" id="server" /> <br /> <br /> <label for="database">Database: -</label> <br /> <input type="text" name="database" id="database" /> <br /> <br /> <input type="submit" value="Login" /> <input type="reset" value="Reset" /> </form> </body> </html> Following is the content of admin.php. By this point I can see the connection in MySQL Workbench, and when I submit the query 'SELECT * FROM subscribers' it's being stored in '$_POST['query']', but 'mysql_query($_POST['query'],$_SESSION['con']);' is returning nothing. There is definitely a record in that table, and the user I'm logging on with has permission to run the 'SELECT' command against this database, so I can't figure out why mysql_query(); is returning nothing: - Code: [Select] <!DOCTYPE HTML> <?php session_start(); if(!$_SESSION['con']) { if(!($_POST['username'] || $_POST['password'])) { if(!($_SESSION['username'] || $_SESSION['password'])) { $error="Username and password variables empty."; } } else { $_SESSION['username']=mysql_real_escape_string($_POST['username']); $_SESSION['password']=mysql_real_escape_string($_POST['password']); $_SESSION['server']=mysql_real_escape_string($_POST['server']); $_SESSION['database']=mysql_real_escape_string($_POST['database']); $_SESSION['con']=mysql_pconnect($_SESSION['server'],$_SESSION['username'],$_SESSION['password']); if(!$_SESSION['con']) { $error="Failed to connect to server."; } else { $database=mysql_select_db($_SESSION['database'],$_SESSION['con']); if(!$database) { $error="Failed to connect to database."; } } } } if(!$_POST['query']) { $error="No query submitted."; } else { $result=mysql_query($_POST['query'],$_SESSION['con']); if(!$result) { $error="Query returned nothing."; } } ?> <html lang="en"> <head> <title>SQL admin interface</title> <meta charset="iso-8859-1" /> </head> <body> <form action="admin.php" method="post"> <textarea name="query" rows="10" cols="50">SELECT * FROM subscribers</textarea> <br /> <br /> <input type="submit" value="Submit query" /> </form> <?php if($error) { echo $_POST['query']."<br /><br />".$result."<br /><br />".$error; die(); } else { while($row=mysql_fetch_assoc($result)) { echo $row['name']." ".$row['email']; echo "<br />"; } } ?> </body> </html> Can anyone help? MOD EDIT: [code] . . . [/code] tags added. Hi All, I am pretty new to PHP ( I am a C Programmer). I am trying a simple shopping cart website for my friend. IN one of the pages, I am submitting some info, which is actually not showing up in my server side php. Below is the HTML code to submit. <a href="cart.php?action=add&p=5&size=small"> <img src="images/add_to_cart.gif"/> </a> I tried to check the values of the parameters using $action = $_GET['action'] ; Action stored empty. Then I checked the whole array print_r($_GET) which returned Array( ) So, for some reason the value is always empty. I tried the declaration GLOBAL $_GET, but no use. Any help/directions - much appreciated! <?php if('00' == '000') echo 'weired'; ?> Please consider the code above. Strangely it echoes the word "weired". Also if('00' == '000000000000000') returns true and so forth. What is really going on? Thanks in advance By the way the php version is 5.3.9 on wampserver 2.2 Hi again everyone! I'm sitting here, developing the same site - on my localhost the site is working great! Then when I upload it, to another testserver (production for developers), I get following: Notice: Undefined variable: db in C:\xampp\htdocs\lucas\sidebar.php on line 3 Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\lucas\inc\functions.php on line 13 I'm wondering why I get it, because if I do a try / catch on the db connection, and do a select * on the content table, it returns results, the paths should be almost the same.. On localhost I run: localhost/lucas/, on the prod-server I run liveip/lucas/ Can any spot the problem? I'm not a big xampp dude myself, I've attached an dump of my PHP info also, just rename the .php to .html Thank you a lot! Lucas R / Zerpex Hi i am running a wamp server on windows 7 i am trying to php exec command to run a command but the output returns 1 does this mean the cmd failed to execute ? Code: [Select] $openssl_cmd = "($OPENSSL mime -sign -signer $MY_CERT_FILE -inkey $MY_KEY_FILE ". "-outform der -nodetach -binary <<_EOF_\n$data\n_EOF_\n) | " . "$OPENSSL smime"." -encrypt -des3 -binary -outform pem $PAYPAL_CERT_FILE"; I have a table called users with a fieldname called service_id. In a table called services I have id and name. I want to query the users table and, based on the service_id, display the name of the service (which is stored in the services table). However, when I try this code I get No records returned. I later echo out under a while statement $row['name']; or $row['id'] $query = "SELECT users.username, users.lname, users.fname, users.service_id, services.name, services.id FROM users, services WHERE users.inst_id = '".$userarray['inst_id']."' and users.id !='".$userarray['id']."' and users.service_id = services.id "; I am trying to unserialize this string: a:3:{s:3:\"zip\";s:5:\"55068\";s:4:\"city\";s:9:\"Rosemount\";s:5:\"state\";s:2:\"MN\";} but I unserialize is returning false. Why is it doing that? $info = unserialize($_COOKIE['zipcode']); var_dump($info); Hi, I am trying to verify if the given url exists or not, by using file_exists() function. It always returns 'FALSE' , according to my understanding it happening because the file to be checked on the given url is located in safe mode. Could anyone please suggest as to how this could be overcome, by similar function or by using alternative method. Regards Abhishek Madhani Me again.. I'm fetching data from MySQL but each person in people.php is displayed two times instead one.. The issue must be inside models_category_tbl table, because each person have more then one result. Any advice is appreciated. What should I do? I would like to display people something like that: 1 John Doe 1 IT developer, 3 mechanic models/model = person category = occupation/skills MySQL: model_index table +---------+------------+-------------+-------------------+---------------+----------------+ |model_id | model_name | model_title | model_description | model_country | model_slug | +---------+------------+-------------+-------------------+---------------+----------------+ | 1 | John Doe | Johns title | Johns desc | Hungary | john-doe | +---------+------------+-------------+-------------------+---------------+----------------+ models_category_tbl table +-------------+---------------------+---------------------+ | category_id | model_category_name | model_category_slug | +-------------+---------------------+---------------------+ | 1 | it developer | it-developer | | 2 | photographer | photographer | | 3 | mechanic | mechanic | +-------------+---------------------+---------------------+ models_category_ids table +----+----------+-------------+ | id | model_id | category_id | | 1 | 1 | 1 | | 1 | 1 | 3 | +----+----------+-------------+
PHP function to fecth data: public function getAllModels1 () { $sql = "SELECT * FROM models_index JOIN models_category_ids ON models_index.model_id=models_category_ids.model_id JOIN models_category_tbl ON models_category_tbl.category_id=models_category_ids.category_id" ; $stmt = $this->conn->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll((PDO::FETCH_OBJ)); return $result; }
people.php <?php declare(strict_types=1); ob_start(); include "includes/connect.php"; include "includes/functions.php"; $model = new ModelsData(); $models = $model->getAllModels1(); foreach ($models as $model) { ?> <a href="model.php?id=<?= $model->model_id ?>"><img src="<?= $model->model_img_path ?><?=$model->model_img_name ?>"></a> <?php echo $model->model_id . " " . $model->model_name . " " . $model->category_id . " " . $model->model_category_name ; ?> <h3><?= $model->model_name ?></h3> <?php } ?>
Output: 1 John Doe 1 IT developer 1 John Doe 3 mechanic
When you do a search at (right sidebar): http://ourneighborhooddirectory.org the $_GET result is always blank. The site is hosted at Bluehost and this is a Wordpress site. You can see the result of the query because I write them out. Here is the form code: Code: [Select] <form method="get" action="http://ourneighborhooddirectory.org/search-results/" > Search the Directory: <input type="text" name="srch"/> <input type="submit" value="Search" /> </form> Here is the PHP code on the action page: <?php $srchVal = $_GET["srch"]; echo $_GET['srch']; echo "------------ ". $srchVal." ------------"; print_r($_GET); echo $_SERVER['QUERY_STRING']; ?> Any ideas on why $_POST and $_GET always return blank? Thanks for the help... |