Jump to content

help with looping through database X times [list]


mikkel809h
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hey everyone:)

 

Im not very good at php and html and all that stuffz, but i've started making a little script which lists my homework in my lessons, which i put into a mysql database.

 

In the "site" im having 5 columns:

 

DANISH - GERMAN - MATH - ENGLISH - OTHER

 

Which is displayed correct.

 

Now... If i have like 2 "posts" in the danish table (in the database), and 5 "posts" in the "other" table.. Then i want the script to loop as many times as the biggest table is carrying.

 

like this:

 

 

listdanish:
id: 1
type: danish
time: 01-11-2013 15:48
desc: Danish homework for now
dlink: download link to the file attached...

All information in this table is having 4 different "inputs" (idk what its called if i put a thing into a table in a database)

Then the script knows that it has to loop atleast 4 times.

 

 

BUT..

 

if the english table is having 6 different "inputs" then

it has to loop 6 times...

 

 

 

So basically the script will loop a code until the tables are fully knowen

 

 

Any help is really appreciated :)

 

-Thanks in advance

 

-Mikkel809h

 

Link to comment
Share on other sites

Oh.. Just saw that i was missing the code...

 

(and i cant edit my post?)

so:

 

code

 <!DOCTYPE html>


<html>
	<head>
		<style>
			body {
				background-color:#d0e4fe;
			}
			{

				a:link,a:visited {
				display:block;
				font-weight:bold;
				color:#FFFFFF;
				background-color:#98bf21;
				width:360px;
				text-align:center;
				padding:10px;
				text-decoration:none;
				border:2px solid;
				border-radius: 5px;
				}
				a:hover,a:active {
					background-color:#7A991A;
				}
			}
		</style>
	</head>

	<body>
		<?php
			if(!isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] != 'true'))
			{
			?>
				<center>
					<a href="secure.html"><img src="/images/badsmiley.png" alt="Smiley face" height=195 width=210></a>
				
					<b>
					<br />
					<font face="Comic Sans MS" size="6" type="bold">
						Åhhh nej!!
						<br />
						Brugernavnet eller kodeordet er forkert!
						<br />
						prøv igen, ved at klikke på smiley'en
					</font>
					</b>
				</center>
			<?php
				exit();
			} elseif(isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] == 'true'))
			{
				$host = "notpublic";
				$db = "notpublic";
				$user = "notpublic";
				$pass = "notpublic";
				if (!mysql_connect($host, $user, $pass)) {
					echo 'Could not connect to mysql';
					exit;
				}
				mysql_select_db($db);

				$sqldansk = "SELECT * FROM listdansk";
				$resultdansk = mysql_query($sqldansk);
				if (!$resultdansk) {
					echo "DB Error, could not list tables in dansk\n";
					echo 'MySQL Error: ' . mysql_error();
					exit;
				}
				$sqltysk = "SELECT * FROM listtysk";
				$resulttysk = mysql_query($sqltysk);
				if (!$resulttysk) {
					echo "DB Error, could not list tables in tysk\n";
					echo 'MySQL Error: ' . mysql_error();
					exit;
				}
				$sqlmatematik = "SELECT * FROM listmatematik";
				$resultmatematik = mysql_query($sqlmatematik);
				if (!$resultmatematik) {
					echo "DB Error, could not list tables in matematik\n";
					echo 'MySQL Error: ' . mysql_error();
					exit;
				}
				$sqlengelsk = "SELECT * FROM listengelsk";
				$resultengelsk = mysql_query($sqlengelsk);
				if (!$resultengelsk) {
					echo "DB Error, could not list tablesin engelsk\n";
					echo 'MySQL Error: ' . mysql_error();
					exit;
				}
				$sqlandet = "SELECT * FROM listandet";
				$resultandet = mysql_query($sqlandet);
				if (!$resultandet) {
					echo "DB Error, could not list tables in andet\n";
					echo 'MySQL Error: ' . mysql_error();
					exit;
				}


				Print "\n<!-- Start of Table -->\n";
				Print "<table border=1 cellpadding=15 width=100%>\n";
				Print "\n<!-- First row (Headings) -->\n";
				Print "<tr>\n";
				Print "    <th width = 20%>DANSK</th>\n";
				Print "    <th width = 20%>TYSK</th>\n";
				Print "    <th width = 20%>ENGELSK</th>\n";
				Print "    <th width = 20%>MATEMATIK</th>\n";
				Print "    <th width = 20%>ANDET</th>\n";
				Print "</tr> \n";
				?>
				<center>
				<?php
					$row = mysql_fetch_row($resultdansk);
					#$id=$row[0];
					#$type=$row[1];
					$time=$row[2];
					$desc=$row[3];
					$dlink=$row[4];
					$dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
					$endprt1=$time.' - '.$dlink2;
					
					$row = mysql_fetch_row($resulttysk);
					#$id=$row[0];
					#$type=$row[1];
					$time=$row[2];
					$desc=$row[3];
					$dlink=$row[4];
					$dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
					$endprt2=$time.' - '.$dlink2;
					
					$row = mysql_fetch_row($resultmatematik);
					#$id=$row[0];
					#$type=$row[1];
					$time=$row[2];
					$desc=$row[3];
					$dlink=$row[4];
					$dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
					$endprt3=$time.' - '.$dlink2;
					
					$row = mysql_fetch_row($resultengelsk);
					#$id=$row[0];
					#$type=$row[1];
					$time=$row[2];
					$desc=$row[3];
					$dlink=$row[4];
					$dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
					$endprt4=$time.' - '.$dlink2;
					
					$row = mysql_fetch_row($resultandet);
					#$id=$row[0];
					$type=$row[1];
					$time=$row[2];
					$desc=$row[3];
					$dlink=$row[4];
					$dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
					$endprt5=$time.' - '.$type.' - '.$dlink2;
					Print "    <td width = 20% align=center>".$endprt1."</td>\n";
					Print "    <td width = 20% align=center>".$endprt2."</td>\n";
					Print "    <td width = 20% align=center>".$endprt3."</td>\n";
					Print "    <td width = 20% align=center>".$endprt4."</td>\n";
					Print "    <td width = 20% align=center>".$endprt5."</td>\n";

				?>
				</center>
				<?php
			}
		?>
	</body>
</html>
Link to comment
Share on other sites

Just calling  mysql_fetch_row on its own only returns the first record from the query. If your queries return more than one record you need to be looping through the results, eg

$result = mysql_query(/* YOUR QUERY */);
while($row = mysql_fetch_row($result))
{
   // process the results
}
Link to comment
Share on other sites

You start off mentioning "columns" in your post then you switch to "tables". Can you be precise?

 

What is the structure of the relevant tables in your database?

Oh.. Well On the site im having columns which represent the type of homework... like

 

--DANISH--

| |

| Here is the danish thingy |

| |

---------

 

and the same for the other types.

 

Then when talking about databases i meant that im having a database, which stores 5 different tables.

The 5 different tables is the different types of homework, like:

 

table1:

listdanish

table2:

listgerman

table3:

listmath

 

 

etc...

 

 

Then the website script ( the code i provided ) is reading all thoose different tables and is going to print the different types and time etc...

 

But...

 

as i want it to loop through everything until it've reached the last information knowen, then it has to stop

(These pictures is written in danish... thats why you maybe wont understand whats written,,,

the written columns:

Danish  German  English  Math  Other

)

like this:Screenshot%202013-11-02%2012.56.36%20-%2

 

But at the moment it wont loop like that...

 

(i edited the normal screenshot to get that image above)

 

The picture im having now is:

Screenshot%202013-11-02%2012.56.36.png?d

 

And if i wanted to put llike 2 different "informations" in the listdanish table, then this has to update the whole row. of columns

 

 

 

 

 

 

 

Just calling  mysql_fetch_row on its own only returns the first record from the query. If your queries return more than one record you need to be looping through the results, eg

$result = mysql_query(/* YOUR QUERY */);
while($row = mysql_fetch_row($result))
{
   // process the results
}

Well.. if you look through the above comment ( and the code i provided ) then

you would see that im having more than only one table to look in.

so that wont be possible..

 

I need like a thing that loops through all the tables and adds the numbers to each other...

 

 

 

Thanks in advance

 

- If you want more info, please tell me as im quite new :)

 

 

-Mikkel809h

Edited by mikkel809h
Link to comment
Share on other sites

You have not understood my reply.

 

For each of your results (which are $resultdansk, $resulttysk, $resultmatematik, $resultengelsk and $resultandet) you need to use a separate while loop. 

 

Example while loop codes for the DANSK and TYSK columns

// check that query for DANSK returned any results
if(mysql_num_rows($resultdansk))
{
    $endprt1 = '';
    // loop through all results for DANSK
    while($row = mysql_fetch_row($resultdansk))
    {
        #$id=$row[0];
        #$type=$row[1];
        $time=$row[2];
        $desc=$row[3];
        $dlink=$row[4];
        $dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
        $endprt1 .= $time.' - '.$dlink2; // concatenate each download link to $endprt1 variable
    }
}
else
{
    $endprt1 = '-'; // no results for DANSK
}

// check that query for TYSK returned any results
if(mysql_num_rows($resulttysk))
{
    ​$endprt2 = '';
    // loop through all results for TYSK
    while($row = mysql_fetch_row($resulttysk))
    {
        #$id=$row[0];
        #$type=$row[1];
        $time=$row[2];
        $desc=$row[3];
        $dlink=$row[4];
        $dlink2='<a href="'.$dlink.'">'.$desc.'</a><br />';
        $endprt2 .= $time.' - '.$dlink2; // concatenate each download link to $endprt2 variable
    }
}
else
{
    $endprt2 = '-'; // no results for TYSK
}

//etc...
// do the same for the $resultmatematik, $resultengelsk and $resultandet results
Edited by Ch0cu3r
Link to comment
Share on other sites

Oh Okay,

 

So i "just" need to check if the info exists 1 time, then if it does then it loops and tells endprt to be that?

 

whats that $endprt1 . <- that little dot, for? is that so it extends the current data in this variable?

 

hmm... well How do i then check for how many times / rows to print?

is it by doing the foreach?

 

im so sorry if im a retard.... (yes i am...) but im still in the learning of the php etc..

 

 

 

Thanks

Edited by mikkel809h
Link to comment
Share on other sites

The .= is the concatenation assignment operator

http://php.net/manual/en/language.operators.string.php

 

Example

$var  = 'hello ';
$var .= 'world';
echo $var; // prints hello world

// The .=  is the same as
$var = $var . 'world';
echo $var;
 

I used this operator so as it loop through the results it'll add each download link to the $endprt* variable. So when you echo these variables in the table you'll see the links are listed.

Edited by Ch0cu3r
Link to comment
Share on other sites

Okay

 

Well thats a nice method of doing that :-D

So.. back to topic:

 

the $endprt1 is returning :

time() . '<a href="'.$dlink.'">'.$desc.'</a><br />' . time() . '<a href="'.$dlink.'">'.$desc.'</a><br />'; -- as many times as there exists a information in the table..

Then.... if I have to print 1 piece of this (like the first of all the variables) then i have to first kinda 'select' the thing until it comes to the next "time" symbol.

Then it has to print everything as many times as there exists something in the $endprt1...

 

I just made an example in LUA ( if you know lua )

 

maxtimestoloop = 0;
dansktimes = 0;
tysktimes = 0;
matematiktimes = 0;
engelsktimes = 0;
andettimes = 0;
local listdansk = {[1]={"id","dansk","time","desc","dlink"};
local listtysk = {[1]={"id","tysk","time","desc","dlink"};
local listmatematik = {[1]={"id","matematik","time","desc","dlink"};
local listengelsk = {[1]={"id","engelsk","time","desc","dlink"};
local listandet = {[1]={"id","andet","time","desc","dlink"};
 
--#// Get how many times to loop the printing in the columns \\#--
for list in pairs(listdansk) do
dansktimes = dansktimes + 1;
end
for list in pairs(listtysk) do
tysktimes = tysktimes + 1;
end
for list in pairs(listmatematik) do
matematiktimes = matematiktimes + 1;
end
for list in pairs(listengelsk) do
engelsktimes = engelsktimes + 1;
end
for list in pairs(listandet) do
andettimes = andettimes + 1;
end
 
maxtimestoloop = math.max(dansktimes,tysktimes,matematiktimes,engelsktimes,andettimes);
 
for i = 1, maxtimestoloop do
print("loop "..i);
end
 

 

 

Its hard to explain, but is the math.max in the php version?, so i can do like a look until currenttimes is equal to the maxtimes to loop

 

 

Thanks

Link to comment
Share on other sites

Sounds like you want to have the results in an array rather than a concatenated list.

 

I have modified the code for this however it is untested.

 <!DOCTYPE html>


<html>
    <head>
        <style>
            body {
                background-color:#d0e4fe;
            }
            {

                a:link,a:visited {
                display:block;
                font-weight:bold;
                color:#FFFFFF;
                background-color:#98bf21;
                width:360px;
                text-align:center;
                padding:10px;
                text-decoration:none;
                border:2px solid;
                border-radius: 5px;
                }
                a:hover,a:active {
                    background-color:#7A991A;
                }
            }
        </style>
    </head>

    <body>
        <?php
            if(!isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] != 'true'))
            {
            ?>
                <center>
                    <a href="secure.html"><img src="/images/badsmiley.png" alt="Smiley face" height=195 width=210></a>
                
                    <b>
                    <br />
                    <font face="Comic Sans MS" size="6" type="bold">
                        Åhhh nej!!
                        <br />
                        Brugernavnet eller kodeordet er forkert!
                        <br />
                        prøv igen, ved at klikke på smiley'en
                    </font>
                    </b>
                </center>
            <?php
                exit();
            }
            elseif(isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] == 'true'))
            {
                $host = "notpublic";
                $db = "notpublic";
                $user = "notpublic";
                $pass = "notpublic";
                if (!mysql_connect($host, $user, $pass)) {
                    echo 'Could not connect to mysql';
                    exit;
                }
                mysql_select_db($db);

                $sqldansk = "SELECT * FROM listdansk";
                $resultdansk = mysql_query($sqldansk);
                if (!$resultdansk) {
                    echo "DB Error, could not list tables in dansk\n";
                    echo 'MySQL Error: ' . mysql_error();
                    exit;
                }
                $sqltysk = "SELECT * FROM listtysk";
                $resulttysk = mysql_query($sqltysk);
                if (!$resulttysk) {
                    echo "DB Error, could not list tables in tysk\n";
                    echo 'MySQL Error: ' . mysql_error();
                    exit;
                }
                $sqlmatematik = "SELECT * FROM listmatematik";
                $resultmatematik = mysql_query($sqlmatematik);
                if (!$resultmatematik) {
                    echo "DB Error, could not list tables in matematik\n";
                    echo 'MySQL Error: ' . mysql_error();
                    exit;
                }
                $sqlengelsk = "SELECT * FROM listengelsk";
                $resultengelsk = mysql_query($sqlengelsk);
                if (!$resultengelsk) {
                    echo "DB Error, could not list tablesin engelsk\n";
                    echo 'MySQL Error: ' . mysql_error();
                    exit;
                }
                $sqlandet = "SELECT * FROM listandet";
                $resultandet = mysql_query($sqlandet);
                if (!$resultandet) {
                    echo "DB Error, could not list tables in andet\n";
                    echo 'MySQL Error: ' . mysql_error();
                    exit;
                }


                Print "\n<!-- Start of Table -->\n";
                Print "<table border=1 cellpadding=15 width=100%>\n";
                Print "\n<!-- First row (Headings) -->\n";
                Print "<tr>\n";
                Print "    <th width = 20%>DANSK</th>\n";
                Print "    <th width = 20%>TYSK</th>\n";
                Print "    <th width = 20%>ENGELSK</th>\n";
                Print "    <th width = 20%>MATEMATIK</th>\n";
                Print "    <th width = 20%>ANDET</th>\n";
                Print "</tr> \n";

                // Created this function to get the results from the queries
                function getResults(&$result)
                {
                    $links = array();

                    if(mysql_num_rows($result))
                    {
                        while($row = mysql_fetch_row($result))
                        {
                            #$id=$row[0];
                            #$type=$row[1];
                            $time   =$row[2];
                            $desc   =$row[3];
                            $dlink  = $row[4];

                            // add link to $links array
                            $links[] = $time.' - <a href="'.$dlink.'">'.$desc.'</a>';
                        }
                    }

                    return $links; // return an array of links
                }

                $links = array();
                $links['DANSK']     = getResults($resultdansk);        // get links for dansk
                $links['TYSK']      = getResults($resulttysk);         // get links for tysk
                $links['MATEMATIK'] = getResults($resultmatematik);    // get links for atematik
                $links['ENGELSK']   = getResults($resultengelsk);      // get links for engelsk
                $links['ANDET']     = getResults($resultandet);        // get links for andet


                // loop through each link category 
                // and count how many links it has
                $count = array();
                foreach($links as $linkCategory)
                    $count[] = count($linkCategory);

                // get the maximum number to loop
                $maxCount= max($count);

                // loop over maxCount printing the links
                for($i = 0; $i < $maxCount; $i++)
                {
                    // get link for current loop position ($i)
                    //         check if link exists           ?   get the link          :  no link
                    $endprt1 = isset($links['DANSK'][$i])     ? $links['DANSK'][$i]     : '-';
                    $endprt2 = isset($links['TYSK'][$i])      ? $links['TYSK'][$i]      : '-';
                    $endprt3 = isset($links['MATEMATIK'][$i]) ? $links['MATEMATIK'][$i] : '-';
                    $endprt4 = isset($links['ENGELSK'][$i])   ? $links['ENGELSK'][$i]   : '-';
                    $endprt5 = isset($links['ANDET'][$i])     ? $links['ANDET'][$i]     : '-';

                    // output the link for current position.
                    print "<tr>";
                    Print "    <td width = 20% align=center>".$endprt1."</td>\n";
                    Print "    <td width = 20% align=center>".$endprt2."</td>\n";
                    Print "    <td width = 20% align=center>".$endprt3."</td>\n";
                    Print "    <td width = 20% align=center>".$endprt4."</td>\n";
                    Print "    <td width = 20% align=center>".$endprt5."</td>\n";
                    print "</tr>";
                }

                print "</table>";
            }
        ?>
    </body>
</html>
Link to comment
Share on other sites

Firstly, I would restructure your data. A single table like this

mysql> SELECT * FROM homework;
+------------+------------+---------+-------------+
| idhomework | hwdate     | subject | description |
+------------+------------+---------+-------------+
|          1 | 2013-11-02 | OTHER   | Other100    |
|          2 | 2013-11-02 | DANISH  | Danish101   |
|          3 | 2013-11-02 | ENGLISH | English102  |
|          4 | 2013-11-02 | OTHER   | Other103    |
|          5 | 2013-11-03 | MATH    | Math104     |
|          6 | 2013-11-03 | MATH    | Math105     |
|          7 | 2013-11-03 | MATH    | Math106     |
|          8 | 2013-11-03 | DANISH  | Danish107   |
|          9 | 2013-11-04 | OTHER   | Other108    |
|         10 | 2013-11-04 | GERMAN  | German109   |
|         11 | 2013-11-04 | MATH    | Math110     |
|         12 | 2013-11-04 | OTHER   | Other111    |
|         13 | 2013-11-04 | GERMAN  | German112   |
|         14 | 2013-11-05 | MATH    | Math113     |
|         15 | 2013-11-06 | MATH    | Math114     |
|         16 | 2013-11-06 | DANISH  | Danish115   |
|         17 | 2013-11-06 | ENGLISH | English116  |
|         18 | 2013-11-06 | MATH    | Math117     |
|         19 | 2013-11-06 | MATH    | Math118     |
|         20 | 2013-11-07 | GERMAN  | German119   |
|         21 | 2013-11-07 | DANISH  | Danish120   |
|         22 | 2013-11-07 | GERMAN  | German121   |
|         23 | 2013-11-07 | OTHER   | Other122    |
|         24 | 2013-11-07 | ENGLISH | English123  |
|         25 | 2013-11-08 | DANISH  | Danish124   |
|         26 | 2013-11-08 | GERMAN  | German125   |
|         27 | 2013-11-08 | OTHER   | Other126    |
|         28 | 2013-11-09 | OTHER   | Other127    |
|         29 | 2013-11-09 | MATH    | Math128     |
|         30 | 2013-11-09 | ENGLISH | English129  |
|         31 | 2013-11-09 | OTHER   | Other130    |
|         32 | 2013-11-09 | OTHER   | Other131    |
|         33 | 2013-11-10 | MATH    | Math132     |
|         34 | 2013-11-11 | DANISH  | Danish133   |
|         35 | 2013-11-11 | ENGLISH | English134  |
|         36 | 2013-11-11 | OTHER   | Other135    |
+------------+------------+---------+-------------+

Then you can produce an HTML table like this (first bit of code creates test data)

<?php
include("/db_inc.php");
$db = new mysqli(HOST,USERNAME,PASSWORD,'test');

/**************************************************************
* Create table with normalized structure
***************************************************************/
   
$sql = "CREATE TABLE homework (
        idhomework INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        hwdate  DATE,
        subject VARCHAR(10),
        description VARCHAR(255)
    )";
// $db->query($sql);

/**************************************************************
* Create some random test data
***************************************************************/
   
$subjects = array('DANISH','GERMAN','MATH','ENGLISH','OTHER');
$recs = array();
$n = 100;
$dt = new DateTime();
$dp = new DatePeriod($dt, new DateInterval('P1D'), 10);
foreach ($dp as $date) {
    $k = rand(1,5);     // how many assignments this day
    for ($i=0; $i<$k; $i++) {
        $subj = $subjects[array_rand($subjects)];   // get random subject
        $desc = ucfirst(strtolower($subj)) . $n++;  // create a description
        $recs[] = sprintf("('%s', '%s', '%s')", $date->format('Y-m-d'),$subj, $desc);
    }
}

$sql = "INSERT INTO homework(hwdate,subject,description) VALUES\n" . 
        join(",\n", $recs);
// $db->query($sql);

/****************************************************************
* Query the data and display in HTML table
*****************************************************************/

$template = array_fill_keys($subjects, array()); // create empty array
$tableHead = "<tr><th>Date</th><th>" . join('</th><th>', $subjects) . '</th></tr>';
echo "<table border='1' cellpadding='5' style='border-collapse:collapse'>$tableHead\n";

$sql = "SELECT hwdate, subject, description
        FROM homework
        ORDER BY hwdate, subject";
$res = $db->query($sql);

$curdate = '';
while ($row = $res->fetch_assoc()) {
    if ($row['hwdate'] != $curdate) {
        if ($curdate) {
            echo "<tr style='vertical-align: top'><td>$curdate</td>";
            foreach ($assignments as $arr) {
                echo '<td>' . join('<br>', $arr) . '</td>';
            }
            echo "</tr>\n";
        }
        $assignments = $template;
        $curdate = $row['hwdate'];
    }
    $assignments[$row['subject']][] = $row['description'];
}
// don't forget last date
echo "<tr style='vertical-align: top'><td>$curdate</td>";
foreach ($assignments as $arr) {
    echo '<td>' . join('<br>', $arr) . '</td>';
}
echo "</tr>\n";
echo "</table>\n";

?>

Which gives the attached output.

post-3105-0-63015900-1383411619_thumb.png

Link to comment
Share on other sites

Ohhh... Woow.. I didnt know that it could be done that 'easy' and short.

Thank you guys!

 

Now i have another question:

 

If i want 5 different radio buttons on another page, which displays:

DANSK

TYSK

MATEMATIK

ENGELSK

ANDET

 

.. Then when i chose one of the radiobuttons, then  4 text fields and 1 submit button comes visible

The 4 text fields is:

the TYPE

the TIME

the DESC ( or the name )

and then

the DLINK.

 

Then when i click submit, then the script goes to the choosen lesson ( one of the radio buttons choosed ), and then it goes to the database into that table, and inserts all the information from the text fields...

 

 

Is that possible without having 5 different pagename.html sites?

 

and what animations would be nice to use when the text fields appear?

 

 

 

Thanks for everything done so far!

 

 

- Mikkel

Link to comment
Share on other sites

  • Solution

You don't need separate pages. Only one. You can have the form submit to itself. When the form is submitted you add the course details to your database. Example

<?php

if(isset($_POST['submit']))
{
    // see what is in the _POST
    printf('<pre>%s</pre>', print_r($_POST, 1));

    // add the course details to the database here
    echo 'TODO: Add course to database';
}

?>
<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                 // on page load hide the fields within div#fields
                if($('input[name="course"]:checked').length === 0) {
                    $('#fields').hide();
                }

                // when user selects a course slide fields into view
                $('input[name="course"]').bind('click', function(e) {
                    $('#fields').slideDown();
                });
            });
        </script>
    </head>

    <body>

        <?php

        // list courses in an array
        $courses = array('DANSK', 'TYSK', 'MATEMATIK', 'ENGELSK', 'ANDET');

        ?>

        <form method="post">

            <div id="course">
                <dt>Course:
                <?php 
                // loop through courses and output radio button
                foreach($courses as $course): 
                    $checked = (isset($_POST['course']) && $_POST['course'] == strtolower($course)) ? ' checked' : null;
                ?>
                    <dd><input type="radio" name="course" value="<?php echo strtolower($course) ?>" <?php echo $checked ?> /> <?php echo $course; ?></dd>
                <?php endforeach ?></dt>
            </div>

            <div id="fields">
                <p>Type: <input type="text" name="type"></p>
                <p>Time: <input type="text" name="time"></p>
                <p>Desc: <textarea name="desc"></textarea></p>
                <p>Dlink: <input type="text" name="dlink"></p>
                <p><input type="submit" name="submit" value="Add" /></p>
            </div>
        </form>

    </body>
</html>

 

and what animations would be nice to use when the text fields appear?

I have used JQueries slideDown animation for sliding the fields into view. You can use whatever animation you like.

Link to comment
Share on other sites

Okay.. 
 
but when im trying to insert into then it errors with a parse error:



Parse error: syntax error, unexpected T_STRING in [/size]/home/a3889853/public_html/makenew.html on line [/size]24

if (isset($_POST['type'])) {
			if (isset($_POST['time'])) {
				if (isset($_POST['desc'])) {
					if (isset($_POST['dlink'])) {
						$typ = 'list'.$_POST['type'];
			//LINE 24               $resultcourse = mysql_query(INSERT INTO $typ (type,time,desc,dlink) VALUES ($_POST['type'],$_POST['time'],$_POST['desc'],$_POST['dlink']));
						//$resultcourse = mysql_query($sqlcourse);
						if (!resultcourse) {
							echo 'DB Error! cannot insert course';
							exit();
						}
					} else{
						echo 'Please specify the Dlink!';
						?>
						<a href="choose.html">back</a>
						<?php
					}
				} else{
					echo 'Please specify the Dlink!';
					?>
					<a href="choose.html">back</a>
					<?php
				}
			} else{
				echo 'Please specify the Dlink!';
				?>
				<a href="choose.html">back</a>
				<?php
			}
		} else{
			echo 'Please specify the Dlink!';
			?>
			<a href="choose.html">back</a>
			<?php
		}

 


but if i changed it to this:


Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a3889853/public_html/makenew.html on line 24
 

if (isset($_POST['type'])) {
if (isset($_POST['time'])) {
if (isset($_POST['desc'])) {
if (isset($_POST['dlink'])) {
$typ = 'list'.$_POST['type'];
$sqlcourse = "INSERT INTO $typ (type,time,desc,dlink) VALUES ($_POST['type'],$_POST['time'],$_POST['desc'],$_POST['dlink'])";
$resultcourse = mysql_query($sqlcourse);
//$resultcourse = mysql_query($sqlcourse);
if (!resultcourse) {
echo 'DB Error! cannot insert course';
exit();
}
} else{
echo 'Please specify the Dlink!';
?>
<a href="choose.html">back</a>
<?php
}
} else{
echo 'Please specify the Dlink!';
?>
<a href="choose.html">back</a>
<?php
}
} else{
echo 'Please specify the Dlink!';
?>
<a href="choose.html">back</a>
<?php
}
} else{
echo 'Please specify the Dlink!';
?>
<a href="choose.html">back</a>
<?php
}

 



Whats wrong with that code?

Edited by mikkel809h
Link to comment
Share on other sites

 

Parse error: syntax error, unexpected T_STRING in [/size]/home/a3889853/public_html/makenew.html on line [/size]24

$resultcourse = mysql_query(INSERT INTO $typ (type,time,desc,dlink) VALUES ($_POST['type'],$_POST['time'],$_POST['desc'],$_POST['dlink'])); // LINE 24

Because the query needs to be wrapped in quotes! Also it is a bad idea adding raw $_POST values into an SQL query. Use msyql_real_escape_string to sanitize it

 

Using my example in reply #13 this is how I'd insert the data to the database

<?php
// connect to database first

// check form has been submitted
if (isset($_POST['submt']))
{
    // add an any errors to an array
    $errors = array();

    //check that type field is not empty
    if(empty($_POST['type']))
    {
        $error[] = 'Type'; // Add type to errors
    }

    // check that desc field is not empty
    if(empty($_POST['desc']))
    {
        $error[] = 'Desc'; // Add Desc to errors
    }

    // check that dlink field is not empty
    if(empty($_POST['dlink']))
    {
        $error[] = 'DLink';  // Add DLink to errors
    }

    // only insert record to database if $errors is empty
    if(empty($errors))
    {
        // sanitize input before you use it in the query
        $type  = mysql_real_escape_string($_POST['type']);
        $desc  = mysql_real_escape_string($_POST['desc']);
        $dlink = mysql_real_escape_string($_POST['dlink']);
        $time  = mysql_real_escape_string($_POST['time']);

        $typ = 'list'.$type;
        
        // execute query to add record to database
        $resultcourse = mysql_query("INSERT INTO $typ (type,time,desc,dlink) VALUES ('$type', '$time', '$desc', '$dlink')");

        // check query has executed
        if($resultcourse)
        {     
            // check query has added a record to the database
            if(mysql_affected_rows())
            {
                // success!
                echo 'Record added to database';
            }
            // query did not add anything to database
            else
            {
                // Fail!
                echo 'Record was not added to the database';
            }
        }
        else
        {
            echo 'DB Error! cannot insert course';
            exit();
        }

    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                 // on page load hide the fields within div#fields
                if($('input[name="type"]:checked').length === 0) {
                    $('#fields').hide();
                }

                // when user selects a course slide fields into view
                $('input[name="type"]').bind('click', function(e) {
                    $('#fields').slideDown();
                });
            });
        </script>
    </head>

    <body>

        <?php

        // list courses in an array
        $courses = array('DANSK', 'TYSK', 'MATEMATIK', 'ENGELSK', 'ANDET');

        ?>

        <form method="post">

            <?php
            // display the error message here
            if(!emtpy($errors)) {
                echo '<div style="color:red">Please specify ' . implode(', ', $error) . '</div>';
            } ?>

            <div id="type">
                <dt>Type:
                <?php 
                // loop through courses and output radio button
                foreach($courses as $course): 
                    $checked = (isset($_POST['course']) && $_POST['course'] == strtolower($course)) ? ' checked' : null;
                ?>
                    <dd><input type="radio" name="type" value="<?php echo strtolower($course) ?>" <?php echo $checked ?> /> <?php echo $course; ?></dd>
                <?php endforeach ?></dt>
            </div>

            <div id="fields">
                <p>Time: <input type="text" name="time"></p>
                <p>Desc: <textarea name="desc"></textarea></p>
                <p>Dlink: <input type="text" name="dlink"></p>
                <p><input type="submit" name="submit" value="Add" /></p>
            </div>
        </form>

    </body>
</html>
Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.