Auto increase variable - php

i have a mysql table with 2 coloumns (firstname and lastname) and i want when i run the (select * from names) query all the values from firstname stored into an autoincrement variable like name1=john name2=george etc. and the same for lastname
surname1=williams surname2=james. i have written this but i cant get it to work
<?php
$name="";
$surname="";
$i =1;
$getinfo = "select * from names ";
$query = mysql_query($getinfo);
while ($row = mysql_fetch_array($query)) {
$name.$i. = $row['firstname'];
$surname.$i = $row['lastname'];
}
$i ++;
?>

To achieve what you want, you will need to use this syntax:
$i = 1;
while ($row = mysql_fetch_array($query)) {
${'name'.$i} = $row['firstname'];
${'surname'.$i} = $row['lastname'];
$i++;
}
But this is not a clean way to do so. I recommend you use arrays such as:
while ($row = mysql_fetch_array($query)) {
$names[] = $row['firstname'];
$surnames[] = $row['lastname'];
}

This is possible, but a pretty strange thing to do:
while ($row = mysql_fetch_array($query)) {
++$i;
$nameKey='name'.$i;
$surnameKey='name'.$i;
$$nameKey = $row['firstname'];
$$surnameKey = $row['lastname'];
}
Instead why don't you simply use numeric arrays?
while ($row = mysql_fetch_array($query)) {
$name[] = $row['firstname'];
$surname[] = $row['lastname'];
}
Or, even more elegant:
while ($row = mysql_fetch_array($query)) {
$persons[] = [
'name' => $row['firstname'],
'surname' => $row['lastname']
];
}

Related

Most efficient way to echo PHP prepared statements

I have an SQL query which I have recently turned into a prepared statement for security purposes. I have a query which returns many rows, each consisting of many columns. My question is how to echo the results using a while loop. My example I have so far:
$stmt = $conn->prepare("SELECT * FROM Customers
WHERE travel_Date >= ?
AND travel_Date <= ?
".$searchOption."
LIMIT ?
OFFSET ?");
$todayDateFrom = $todayDate." 00:00:00";
$todayDateTo = $todayDate." 23:59:59";
$stmt->bind_param("ssii", $todayDateFrom, $todayDateTo, $limit, $offset);
$stmt->execute();
while ($stmt->fetch()) {
//echo first name
//echo surname
//echo address
//echo number
//echo type
//15 other things i need to print off
}
I'm not sure what the best way to do this is. I have thought about:
$stmt->bind_result($firstName, $surname, $address, //etc);
But I'm wondering if there's another alternative similar to unprepared statements:
while($row = mysqli_fetch_array($query)){
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
//etc
}
try this:
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
}
try this -
$result_arr = array();
while($row = $stmt->fetch()){
$record = array();
$record['firstname'] = $row['firstname']; // if your db column contains firstname column other wise you can also use $row[0];
$record['name'] = $row[1]; // end so on .......
$result_arr[] = $record;
}
hope this will work for u...

How to contain a while loop in a variable

I have the following code:
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings WHERE location = '$locationListResults' AND industry = '$selected'");
while($row = mysqli_fetch_array($results))
{
echo $row['industry'];
echo $row['location'];
echo $row['title'];
echo $row['description'];
}
}
mysqli_close($con);
}
?>
Could anyone tell me how I would go about storing the echo part into a variable so I can then display it as and where I want in other parts of the site?
If I remove the echo and instead store $row as a variable when I echo that variable it only outputs once and doesn't run the loop.
You should use mysqli_fetch_all for this. The result will be an array where each element is a row and each row is an associative array with the same keys as row in your example
$data = mysqli_fetch_all($result);
$data[0]["industry"]; //Data in the first row
You can then loop over $data to output it any place on your page.
put in array,
$list = array();
while($row = mysqli_fetch_array($results))
{
$list[] = $row;
}
you may try this
$arrayList = array();
while($row = mysqli_featch_array($results)){
$arrayList[] = $row;
}
print_r($arrayList);
Put all the values in an array
$rows = array();
$x = 0;
while($row = mysqli_fetch_array($results))
{
$rows[$x]['industry'] = $row['industry'];
$rows[$x]['location'] = $row['location'];
$rows[$x]['title'] = $row['title'];
$rows[$x]['description'] = $row['description'];
$x++;
}
return $rows;
Then you can use $rows as an array.
foreach($rows as $v){
echo $v['industry']." ".$v['location']."<br />";
echo $v['title']." ".$v['description']."<br />";
}

error printing array when looping over it

Sorry for the relatively newbie question.
Ive been stuck the past hour trying to figure out why the array named $propname does not want to print when i loop over it. Here follows my code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
$id[] = $row['player_id'];
$propName[] = $row['name'];
$propLastName[]= $row['surname'];
}//end while
//create variables for looping
$x = sizeof($propName);
$index = 0;
while($index < $x) //print variables
{
echo $propName[$index];
$index ++;
}
Just simplify your code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
echo $row['name'];
}
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_assoc($result)) //create arrays
{
$id = $row['player_id'];
echo $propName = $row['name'];
$propLastName = $row['surname'];
}

Grab min value in PHP from MySQL Database?

So I have some numbers that take the name "id" in my MySQL database. I tried this code:
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo min($id);
}
On the last line I tried to echo the min value for id, but it didn't work. Any suggestions?
ANSWER: Use "ASC LIMIT 1"
while($row = mysql_fetch_assoc($sql)){
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}
$sql = mysql_query("SELECT * FROM users ORDER BY id ASC LIMIT 1");
while($row = mysql_fetch_assoc($sql))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}
Try this:
$sql = 'SELECT min(id) as min FROM users';
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$min_id = $row['min'];
In case you cannot change the query order (sort by names?), you can determine the lowest $id by using a helper variable:
$min = isset($min) ? min($min, $id) : $id;
And then print $min; after your loop.
If not able to use MIN() in MySQL, try this...
$smallestId = -PHP_INT_MAX;
while($row = mysql_fetch_assoc($sql)) {
...
$smallestId = min($smallestId, $id);
}
If you never have any negative ids (you shouldn't), you could just change -PHP_INT_MAX to 0.

PHP Functions with multiple MySQL results only returning one record

This is the function that im calling.
function GetSubmissions($coach){
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]'") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = explode(",", $teampre);
foreach ($teamarray AS $tkey => $tvalue){
$result = mysql_query("SELECT * FROM `students` WHERE id = '$tvalue'") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $skey => $svalue) { $row[$skey] = stripslashes($svalue); }
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$teamgo .= "$firstname $lastname<br/>";
}
}
$push .= "<div id=submission><div id=event>$event</div><div id=status>$statuspre</div><div id=subinfo>$cat $subcat $division $type</div><div id=team>$teamgo</div></div>";
}
return $push;
}
It works, except its only returning a single result. Ive made little tweaks here and there, but im not seeing any positive changes in the output. Any ideas where im going wrong?
You have nested $result variables. You should try to avoid using the same variable name twice. Renaming the second one inside your second foreach loop would probably do the trick.
You use the same $result for inner loop.

Categories