I have a script like this:
$result = array();
$sql = "SELECT DISTINCT Name FROM servers"; //doesn't really matter what this MySQL script is
//storing the same query in two different variables
$result[0] = mysql_query($sql);
$result[1] = $result[0];
for($i = 0; $i < 3; $i++) {
$result[0] = $result[1];
while($ret = mysql_fetch_array($result[0]) {
//run some code
}
}
Unfortunately, the above code executes once and then for the next iterations returns nothing. What am I doing wrong?
I am not so sure what are you trying to do. but if i understand, try this. remove the for loop, just put the while loop and do what ever you want to.
$sql = "SELECT DISTINCT Name FROM servers";
$result = mysql_query($sql);
while($ret = mysql_fetch_array($result) {
//run some code
echo $ret['Name'];
}
}
you will get all 3 records in each iteration and do what ever process you want to do for each record. no need to make a three 3 query for 3 records. One query will have all records and do while loop to get each record. hope it helps.
Related
I'm having difficulty using a MySQL query in a for loop to produce an array of IDs. Essentially, I have an array of parent IDs which I feed into the query via a for loop and am expecting to return an array of campaign IDs.
Inside the for loop I can echo every campaign ID for every parent ID but can't seem to access this array outside of the loop. I'm assuming this is a scoping issue, and I've fiddled with the code but aren't able to access an array of campaign_ids in its entirety outside of the loop.
My code is as follows:
$campaigns[] = array();
for ($i=0; $i < count($multIO); $i++) {
$sql = 'SELECT DISTINCT campaign_id
FROM prod_appnexus.fact_network_analytics_feed_aggregated_364
WHERE insertion_order_id = '.$multIO[$i]['IO_ID'].';';
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval)) {
$campaigns = $row['campaign_id'];
echo print_r($campaigns);
};
};
Does anybody know how I can troubleshoot this?
Any comments would be greatly appreciated!
Thanks,
Sam
Change the line with this:
$campaigns[] = $row['campaign_id'];
or:
$campaigns[$multIO[$i]['IO_ID']][] = $row['campaign_id'];
Your sql is wrong dont use t1. when you are using single table and also when doing alias dont add as
$campaigns[] = array();
for ($i=0; $i < count($multIO); $i++) {
$sql = 'SELECT DISTINCT campaign_id
FROM fact_network_analytics_feed_aggregated_364 T1
WHERE insertion_order_id = '.$multIO[$i]['IO_ID'].';';
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval)) {
$campaigns = $row['campaign_id'];
echo print_r($campaigns);
};
};
I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
I want the result for this array sql query in one mysql_num_rows
how can I do that? i always get the result for last array query
I have MySQL records example: "1290511", "211223","08910"
$no=array("905","1122","891");
$arrlength=count($no);
for ($x=0; $x<$arrlength; $x++) {
$result = mysql_query(
"SELECT * FROM spe_no WHERE replace(sp_no,' ','') LIKE '%{$cars[$x]}%'"
) or die(mysql_error());
}
while ($row = mysql_fetch_array( $result )) {
$number = $row['sp_numbers'];
echo $number;
}
i always get the last record with "891"
it should all the example
Please help
You are issuing a query multiple times, but only fetching the result set from the last time you issue it. I believe you want this.
for($x=0;$x<$arrlength;$x++) {
$result = mysql_query("SELECT * FROM spe_no WHERE replace(sp_no,' ','') LIKE '%{$cars[$x]}%'") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$number = $row['sp_numbers'];
echo $number;
}
}
Pro tip: Always indent your conditionals and loops so you can see at a glance the logic of your program's flow.
Pro tip: Avoid the mysql_interface, and switch to mysqli or PDO::.
Pro tip: Avoid SELECT *. Instead use a list of columns such as SELECT sp_numbers.
I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}