$variable from fetch_assoc

Hi all,
I’m learning php by basically doing it the idots way. I work with developers and have always been curious. I wanted to create a specific feature and thought I would give it a go and they could help me.

  1. I wanted a form, once filled and submitted that data to be saved in a mysql database.
  2. multipe rows of data but the ID i wanted to search for wasn’t the key. In fact, there was no key. i.e
    (name, last name, car model) so each row could contain multiple duplicate values.

I then wanted a page to have a cell info in the url. The php to use that ‘cell info’ to bring all of the rows that match that.
(so url.com/get.php?id=name)
So all of the rows with ‘name’ in the first row will be displayed.

Amazingly I managed to get this to work via actually hours of google and online tips and tricks.

I then wanted the output to look pretty.
So i learned about using html and php in one file.
Using $variable = ) etc.

The entire block of code that parses the ID from the url, checks the database and echos the rows is as follows:

$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//$name = " . $row["reg"]. ";
$sql="SELECT * from table where name = '".$_GET["id"]."' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      "name: " . $row["name"]. " - car model: " . $row["car_model"];
		

        
    }
} 


else {
    echo "0 results";
}
$conn->close();
?>

Through the great teacher that is google I made great progress.

I then wanted to add html table with css to make it all pretty.

I learned that i could add <style> before the <?php tag and html tables after the close tag.

I learned that I could then use
$first = “” . $row[“reg”];

to create a variable with the info from the database and echo it in my table cells in html.

<?php echo $first; ?>

The problem is, with the
while($row = $result->fetch_assoc()) {
"name: " . $row[“name”]. " - car model: " . $row[“car_model”];

section of code, the php displays all rows that contain the information that i want automaticaly.

But when i do
$first = “” . $row[“reg”];
and echo it, it will only show the values from the very first rows.

How do i attach a $variable to a second row of data?

Sorry if i use bad terminology i am literally just starting out. You have no idea how many hours i have spend on trial and error instead of just taking the time to learn this properly.

Well, yes, you will learn the terminology as time goes by. But, you need to understand what you are doing first. Your WHILE function parses thru ALL of the results of your query one row of data at a time.
Therefore, you can display each row using the same data variables. Loosely like this:

while($row = $result->fetch_assoc()) {
    echo "name: " . $row[“name”]. " - car model: " . $row[“car_model”] . "<br>";
}

This would show a list of all the record “rows” of data in your query results array.

Not sure if this is what you were asking. In your sample code you posted, you did not close your WHILE loop. And, you did not show the ECHO function, so not sure as to what you are asking.

Thank you for your reply, sorry, I skipped some details I think.
Layout of database table:

<
name model
name1 model1
name1 model2
name3 model3
When I use the 'echo' tag, like you said, all of the date that meets that criterea is received. So for each row that contains the matching cell the data is displayed. E.G if the id?=name1 and i use the echo (tag)?
echo "name: " . $row[“name”]. " - car model: " . $row[“model”] . "<br>"

Then the info comes as
name: name1 car model: model1
name: name1 car model: model2

(on a side note, I JUST learned about using the <br> tag. My data was showing as one string e.g
‘name: name1 car model: model1name: name1 car model: model2’**
with no space between the different rows. So thanks a million! )

However trying to get the info into a table:

name model
echo "name: " . $row[“name”]. " model1

Caused all kinds of chaos.

so i removed the ‘echo’ tag so all of the info was fetched but not shown. and to show it I used
$name= “” . $row[“name”];
$name= “” . $row[“model”];

name model
<?php echo $name; ?> <?php echo $model; ?>

Which was a success. so the table shown was:

name model
name1 model1

The problem I am now facing is, for ‘name1’ there are two rows of information and i don’t know how to show both. The info stored is:

<
name model
name1 model1
name1 model2

I don’t know how to
$name="" $row[name"], for the second row.

obviously if I do:


name model
<?php echo $name; ?> <?php echo $model; ?>
<?php echo $name; ?> <?php echo $model; ?>

I get:

name model
name1 model1
name1 model1

Which is just a duplication of the first row instead of the second row.

Oh, okay! What you need to learn is how to create tables infused with data. Easy enough…
This is just off the top of my head and not tested as I am leaving shortly. But, it should get you started!

<table>
    <tr>
        <th>Name</th><th>Car Model</th>
    </tr>
<?PHP
//  create rows of data from database table...
while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row[“name”] . "</td><td>" . $row[“car_model”] . "</td></tr>";
}
?>
</table>

NOTE: As you see this places the PHP code inside the middle of the HTML’s table code.
PHP is handled SERVER-SIDE before the page is sent to the browser. (Browser is CLIENT-SIDE)
Therefore, the user never sees any PHP code, just the outputs of it. More secure that way!
This is just one example. There are lots of ways to do this. Hope this helps…

Thanks,
I wan’t able to get any result with that.

I tried it and when I save brackets gives me no syntax error but when I open the page I only get the headers of the table. no content.


$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql="SELECT * from c2 where first_name = '".$_GET["id"]."' ";
$result = $conn->query($sql);

    
    while($row = $result->fetch_assoc()) {
     "regnumber: " . $row["reg"]. " first name: " . $row["first_name" ] . "<br>" ;
		

    }
$result = $conn->query($sql);

?>

<table>
    <tr>
        <th>Name</th><th>Car Model</th>
    </tr>
<?PHP
//  create rows of data from database table...
while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row[“name”] . "</td><td>" . $row[“car_model”] . "</td></tr>";
}
?>
</table>


If i add the echo tag like: while($row = $result->fetch_assoc()) { echo "regnumber: " . $row["name"]. " first name: " . $row["car_model" ] . "<br>" ;

I am still getting both rows of information.

However with the first code i am getting the error:
Warning : Use of undefined constant “name” - assumed ‘“name”’ (this will throw an Error in a future version of PHP) in localhost on line 36

Notice : Undefined index: “name” in localhost on line 36

Well, first, your query is set to only get one row of data and therefore you would NOT need to use a WHILE statement to loop thru it.
Next, you have two WHILE’s in your code. You can NOT do that. The first one gets all the data from the one row that is returned, then the second one has nothing to put into the table. When PHP is reading the rows of data, it keeps a pointer to the current row. Reading the next row gives nothing for a result because you already read the one row of results. Try this version and see what you get…

$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql="SELECT * from c2 where first_name = '".$_GET["id"]."' ";
$result = $conn->query($sql);
?>

<table>
    <tr>
        <th>Name</th><th>Car Model</th>
    </tr>
<?PHP
//  create rows of data from database table...
while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row[“name”] . "</td><td>" . $row[“car_model”] . "</td></tr>";
}
?>
</table>

And to see ALL of the rows of data, change your query to:

$sql="SELECT * from c2";

You would not want to do that if there are a large number of rows in your database table.
Leaving for the day, but, will check in on your progress tonight when I get back home.
Good luck !


<html>

<head>

<style>

table

{

border-style:solid;

border-width:2px;

border-color:pink;

}
    th, td {
  padding: 15px;
  text-align: left;
}
    tr:hover {background-color: coral;}

</style>

</head>

<body bgcolor="#D3D3D3">


<?php



error_reporting(E_ALL); 
ini_set('display_errors', 1);
$servername = "localhost";
$username = "";
$password = "!";
$db_name = "";

// check connection

$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql="SELECT * from c2 where first_name = '".$_GET["id"]."' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result -> fetch_assoc()){

    // output data of each row
   
      				
		echo '<table border="1">
<tr>
<th>reg number</th>
<th>reg number</th>
<th>first name</th>
<th>Lastname</th>
<th>gender</th>
<th>address</th>
<th>email</th>
</tr>";

    $color = '';
 {
    $color = "style='background-color : green'"; 
}

echo "<tr>";
  echo   "<td $color.>" . $row['reg'] . "</td>";
	echo "<td>" . $row['reg'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
    echo "<td>" . $row['gender'] . "</td>";
    echo "<td>" . $row['address'] . "</td>";
    echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
    
    
   echo '</table>';    
           
echo '<table>";

<tr>
<th>MOT</th>
<th>service</th>
<th>oil</th>
<th>filter</th>
</tr>";      				


echo "<tr>";
	echo "<td>" . $row['MOT'] . "</td>";
echo "<td>" . $row['service'] . "</td>";
echo "<td>" . $row['oil'] . "</td>";
    echo "<td>" . $row['filter'] . "</td>";
    echo "</tr>";
echo "</table>";
}}
   


// duplicate the aboveggg code to duplicate the results.

//no echo here
$conn->close();
?>



I absolutely had this working fully.
I was so happy.
I was getting the first table showing all of the rows that matched “id=”
and then a separate table showing the second set of information.

It was all working and then i messed something up. Something small, simple but I have no idea what.

This is so frustrating. I was so close to acomplishing what I wanted. This was a mini project, I dont think I can go back and learn a whole language for this little quest.

I think will have to admit defeat. I can’t remove an error if I don’t even know what the errors could be. I’m chasing my tail here.

It was a futile effort. I spent so many hours on it. Going through so many iterations. Learing to access mysql, record info in the database, retrieve data via query, retreive data via url variable. Show the info in a syled css way.

I tried a code checker and it says:

  • PHP Syntax Check: Parse error: syntax error, unexpected single-quoted string “;”, expecting “,” or “;” in your code on line 73
    • $color = "style='background-color : green'";

but from what i can see, it says it was expecting the exact thing that is unexpected.

Syntax errors in programming are reported at the point where the language finds something within the current context that is out of place. This is often after the actual problem, because the language has no idea what it is you are attempting to do. You would need to post at least 5 - 10 lines of code before the line with the error for us to help.

If php isn’t reporting syntax errors, it means that the error related settings in the php.ini on your system are not setup to report and display all errors. Since a syntax error prevents your code from ever running, you cannot put these settings in your code and have them show you syntax errors. You would need to find the php.ini that php is using, set error_reporting to E_ALL, set display_errors to ON, restart your web server to get any changes made to the php.ini to take effect, then check using a phpinfo(); statement in a .php script that the settings actually got changed to the desired values.

Edit: if the code in question is the post immediately above the one I replied to, the problem is because you switched from using a single-quote to start a php string, to using a double-quote to close that string.

Programming has/requires a lot of continuity, consistency, and symmetry. In this case, the opening and closing quotes around a string must be the same.

Edit2: There’s also no actual php conditional statement at the point where you are trying to set the $color variable to cause a green background.

Why is there braces around this line of code? Also, all servers have an error log. You can look at that error log and it will tell you what the error is. In this case you said line#36, but we have no idea what line that is. show us the code from line # 30 to line # 40 so we can see it and we can help fix it. As Phdr mentioned, we need to see the code around the area of errors to help you.

I’ve chopping and changing from different tutorials and help posts over the web and have created some kind of frankenstein’s monster.

the code is

echo '<table border="1">
"<tr>"
<th>reg number</th>
<th>reg number</th>
<th>first name</th>
<th>Lastname</th>
<th>gender</th>
<th>address</th>
<th>email</th>
"</tr>";



    **LINE 72**  $color = "style='background-color : green'"; 


echo "<tr>";
  echo   "<td $color.>" . $row['reg'] . "</td>";
	echo "<td>" . $row['reg'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
    echo "<td>" . $row['gender'] . "</td>";
    echo "<td>" . $row['address'] . "</td>";
    echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
    
    
   echo '</table>';

I deleted the brackets to see if it helped.

You are using an echo with multiple lines. It starts with a single quote: echo ’ < table…
This means that it continues until the next single quote which is in the $color = ’ area.
Therefore this will never work. You ended the multiple lines with < / tr >"; You used a double not a single quote for the ending. Therefore it just keeps continuing… I think that change will fix it.

Make the last line "</tr>"; into </tr>'; And it should work.

Thank you so so so much.
I actually learned something from your advice as well as the fix.
I had actually made this mistake at another echo further down the line so the page still didn’t work after this fix.
I read through the code and spotted the same problem.

I feel like I just discovered gravity. :rofl:

Good for you! Always nice to solve a programming puzzle! Good luck from here on…

Sponsor our Newsletter | Privacy Policy | Terms of Service