column name plus one for loop - php

I have name1, name2, name3 in mysql how do a do a 'for loop' to retreive the names of each person in mysql which i need to do for my form validation.
<?php
$row2 = "SELECT * FROM user WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
$result = mysql_query($row2) or die("Error in SQL: " . mysql_error());
$row3 = mysql_fetch_array($result);
?>
In the form, I'm using the following, but it is not retrieving the names:
for($i=1; $i<=5; $i++)
// form code
<?php echo $row3['name'+[$i]]?>');

mysql_fetch_array() returns both numeric and associative keys by default, so your incremental for loop won't give you what you want. Instead, use the MYSQL_ASSOC option or mysql_fetch_assoc()
$row3 = mysql_fetch_assoc($result);
// OR
$row3 = mysql_fetch_array($result, MYSQL_ASSOC);
The for loop has to be done in PHP. It is difficult to tell if your loop is client side or server side.
<?php
for ($i=1; $i<=5; $i++) {
// not 'name' + $i -- PHP uses '.' for concatenation
// but it is easier to interpolate it in double quotes.
echo $row3["name$i"];
}
?>
Update
Since you were trying to mix PHP into a JS loop (which won't work), I recommend instead creating a JavaScript array using PHP, which can then be used in the JS loop later.
<?php
// Open a JS array called namesArray
echo "var namesArray = [";
$names = array();
for ($i=0; $i<=5; $i++) {
// get all the column values into an array
$names[] = '"' . $row3["name$i"] . '"';
}
// Make it into a string
$names = implode(',', $names);
// Close the JS array
echo $names . "];"
?>
That should output something like:
var namesArray = ["val1","val2","val3","val4","val5"];
In your JavaScript loop (which you don't have to change), access the values like:
// Updated to use i-1 instead of i
alert('Please make your colour & shade selection for ' + namesArray[i-1]);

The for loop needs to be inside the php tag.

Related

Store multiple rows from mysql database into one single variable

this is really hard for me, i'm trying to store multiple rows from my table in mysql into a single variable
$mysql_statementJc = "SELECT * FROM `dog`.`cat` WHERE `name` = '$name'";
$mysql_commandJc = mysql_query($mysql_statementJc);
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$groupConcat = $followI . " OR ";
echo $groupConcat;
}
This is my appproach, so at the end of it all i can get "sam, john, bob" saved as $groupConcat which can then be used elsewhere.
Many thanks.
you want to create a concatenated string, php has the .= syntax for this:
$groupConcat='';
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat .= $row['industry'] . " OR ";
}
echo $groupConcat; //no point echoing inside the loop
sometimes a better approach is to use an array and implode()
$groupConcat=array();
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat[] = $row['industry'];
}
echo implode(' OR ',$groupConcat);
Each time through the loop, add the desired value to an array. Then, after the loop, use the implode() function to create your desired output.
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$resultArray[] = $followI;
}
$groupConcat = implode(" OR ", $resultArray);
echo $groupConcat;
Note that you should really stop using the mysql library and instead use mysqli or PDO.
You can also do it as:
$followl = array();
while($row = mysql_fetch_array($mysql_commandJc))
{
$followl[] = $row['industry'];
}
$groupConcat = implode(" OR ",$followl);
echo $groupConcat;
Some Explanation:
Store values into an array $followl and than use implode() function for imploding with OR.
Side note:
Please use mysqli_* or PDO becuase mysql_* is deprecated and no more available in PHP 7.

PHP run query off each array variable and return results in table

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.

How to echo columns 1...n from mysql database except the first one in php?

I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.

calling PHP multi dimensional arrays outside of foreach loop

I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories