I seem to be stuck on a concept in database query and website development.
I have a website that will reflect what data is stored in a database and the website needs to change depending on that data: therefore, my menu system will not be hardcoded in. It builds my menu system based off a query of all the models in my database. The action of clicking on the menu will show tables without changing the page (a simple javascript "showtables" function). like so:
function showTables(TABLE_NAME)
{
if(TABLE_NAME != "PRINTER_TABLE")
{
document.getElementById("PRINTER_TABLE").style.display ="none";
}
if(TABLE_NAME != "show_ALL_PRINTERS")
{
document.getElementById("show_ALL_PRINTERS").style.display ="none";
}
document.getElementById(TABLE_NAME).style.display ="block";
}
I did not include all of my other if statements because there are about 15 of them. These statements will hide everything and the only show the formatted table of "TABLE_NAME" at the end of that script.
My problem is that, if all of the data will not be hardcoded in either HTML or PHP, I need to pass into my function "showTables" a model type or ID that will come from my query.
My Menu system code snipet:
<li class="hasmore"><span>Printer Parts</span>
<ul class="dropdown">
<?php
include 'connection.php';
$query = "SELECT * FROM all_printers";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
#echo "<h3>" . $row['printer_model'] . "</h3>";
echo "<li>" .$row['printer_model']."</li>\n";
}
?>
This puts the model into the menu system and the "PRINTER_TABLE" will access my showTables function, which then will show that table. But there are many different printer models and I need to tell my table query what specific model to get info on.
I hope this makes sense as there is a lot of logic behind it. Maybe there is an easier way..?
In my tables I have:
<table id="table">
<thead>
<tr>
<th scope="col" id="table">Type</th>
<th scope="col" id="table">Size</th>
<th scope="col" id="table">S/N</th>
<th scope="col" id="table">Model</th>
<th scope="col" id="table">Connection Type</th>
<th scope="col" id="table">Surplus</th>
<th scope="col" id="table">Amount</th>
</tr>
</thead>
<tbody>
<?php
include 'connection.php';
$query_misc = "SELECT * FROM all_parts WHERE part_type='MISC'";
$result_misc = mysql_query($query_misc);
while($row = mysql_fetch_array($result_misc))
{
echo "<tr>";
echo "<td><div align=\"center\">".$row['part_type']."</div></td>";
echo "<td><div align=\"center\">".$row['part_size']."</div></td>";
echo "<td><div align=\"center\">".$row['part_sn']."</div></td>";
echo "<td><div align=\"center\">".$row['part_model']."</div></td>";
echo "<td><div align=\"center\">".$row['part_connection']."</div></td>";
echo "<td><div align=\"center\">".$row['part_surplus']."</div></td>";
echo "<td><div align=\"center\">".$row['part_temp_amount']."/".$row['part_amount']."</div></td>";
echo "</tr>";
}
..... etc
Any ideas?
EDIT:
I do now know how to put what I click on, into the url properly..
<?
$query = 'SELECT printer_id, printer_model FROM printer_table WHERE 1 ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
{
echo "<li>" .$product['printer_model']."</li>\n";
}
?>
or
<li><?=$product['printer_model']?></li>
doesnt work properly, because i need to call the suggested part list php part, but do not know where to do so..
EDIT:
I placed that php within a div and the echos will fill out my table, but how am I suppose to call that div to only run when that onclick action? I know that is not how divs work, It would seem I would need a JS function but I know you cannot do php within JS. AJAX perhaps?
EDIT----------------------------------------------------
The call here to the DB is correct, tested it manually without any errors, but I am still receiving a syntax error upon loading my home page. Here is my call to the DB via PHP...
<?
if (!isset($_GET['action']))
{
//If not isset -> set with dumy value
$_GET['action'] = "undefine";
}
include 'connection.php';
$query = 'SELECT ppart_table.* FROM ppart_table LEFT JOIN printer_part_relation ON ppart_table.part_id = printer_part_relation.part_id WHERE printer_part_relation.printer_id ='.mysql_real_escape_string($_GET['printer_id']);
$parts = mysql_query($query) or die("Query failed with error: ".mysql_error());
while ($row = mysql_fetch_assoc($parts))
{
echo table blah blah
}
?>
I have tried supressing all errors via this:
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
And the syntax error at page load still exist.
My home page of this site does NOT have the "product_id=" after mysite.php
I would recommend using PHP's PDO class for database access. I would also recommend using JQuery for all of you javascripting. It makes things VERY simple. It would also be advantagious to keep your display code away from your business logic (two languages should for the most part not be in the same source file ie: HTML/PHP/Javascript). I will stick with what is familiar for now however. perhaps something like this?
menu
<ul>
<?
$query = 'SELECT id, name FROM product_category_table WHERE 1 ORDER BY name';
$product_categories = mysql_query($query);
while ($product_category = mysql_fetch_assoc($product_categories)) :
?>
<li>
$product_category['name']
<ul id="<?= $product_category['id'] ?>" style="display: none;">
<?
$query = 'SELECT id, name FROM product_table WHERE category_id = ' . $product_category['id'] . ' ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
?>
<li><?= $product['name'] ?></li>
<?
endwhile;
?>
</ul>
</li>
<?
endwhile;
?>
</ul>
javascript
function toggleVisibility(category) {
var element = document.getElementById(category);
if (element.style.display == 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
part list
<?
$query = 'SELECT part_table.* FROM part_table LEFT JOIN product_to_part_associations_table ON parts_table.id = product_to_part_associations_table.part_id WHERE product_to_part_associations_table.product_id = ' . mysql_real_escape_string($_GET['product_id']);
$parts = mysql_query($query);
while ($part = mysql_fetch_assoc($parts)) {
echo part table blah blah
}
?>
db tables
product_category_table
id, name, etc
product_table
id, category_id, name, etc
part_table
id, name, etc
part_to_product_association_table
id, product_id, part_id
set the proper indexes on your table columns for speed. the part_to_product_association table allows for a many to many relationship between records in the product table and records in the parts table (needed in the case one part could be used in multiple products, and one product can use multiple parts).
Related
I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code
Controller
function upgradeprofile() {
// $this->load->database();
$this->load->model('freemember_model');
$this->freemember_model->upgrade();
}
model
function upgrade() {
$query = $this->db->get('free_members');
foreach ($query->result() as $row) {
$this->db->where('id', $member_id);
$this->db->insert('domestic_members', $row);
}
}
View
<center> Search Member:
<input type="text" name ='search' id='search' placeholder="Search a member"/></center>
<input type="hidden" name ='limit_from' id='limit_from'/>
</form>
<br><center><button type="button" onclick="CallPrint1('background12')">Print</button>
<div id="background12" class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr#</th>
<th><center>Full Name</th>
<th><center>Mobile Number</th>
<th><center>Membership# / CNIC</th>
<th><center>Email Address</th>
<th><center>Province</th>
<th><center>District</th>
<th><center>Tehsil</th>
<th><center>Union Council</th>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Delete</th>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Print</th>
<th><center>Edit</th>
<th><center>Change Pwd</th>
<th><center>Upgrade</th>
<?php endif;?>
</tr>
</thead>
<tbody>
<?php $sr=0;?>
<?php foreach ($freemembers as $member): ?>
<tr><td><center><?php echo $sr+=1; ?></td><td><center><?php echo $member->first_name; ?></td>
<td><center><?php echo $member->mobile; ?></td><td><center><?php echo $member->cnic; ?></td>
<td><center><?php echo $member->email; ?></td>
<td><center><?php echo $member->province; ?></td><td><center><?php echo $member->district; ?></td><td><center><?php echo $member->tehsil; ?></td><td><center><?php echo $member->uc; ?></td>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>delete</td>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>print</td>
<td><center>edit</td>
<td><center>change pwd</td>
<td><center>Upgrade</td>
<?php endif;?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
this is the view of my table free_members
Based upon your View, you have this...
index.php/admin/upgradeprofile/" . $member->id
So if $member->id = 100 the url will be
index.php/admin/upgradeprofile/100
So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.
So you need to get a handle on the member_id...
This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...
Controller
function upgradeprofile($member_id) {
// Need to check that $member_id is an integer
// To be added by the OP
$this->load->model('freemember_model');
// $member_id is passed in via the URL.
$this->freemember_model->upgrade($member_id);
}
Model
function upgrade() {
// Which member do we want to get from the free_members Table?
$this->db->where('id', $member_id);
$query = $this->db->get('free_members');
// Did we get a result? i.e was a valid member id passed in?
if($query !== false) {
$row = $query->row();
$this->db->insert('domestic_members', $row);
} else {
// Do nothing or handle the case where an illegal number was used...
}
}
Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.
So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.
The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).
So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?
If you need further explanation - ask.
One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...
I'm not familiar with Codeigniter but MySQL syntax should be this:
INSERT INTO table1 (table1.row1, table1.row2)
SELECT table2.row1, table2.row2
FROM table2
WHERE PUT_YOUR_CONDITION_IF_NEEDED
I've found this for Codeigniter.
I'm building an exam management website and one of the pages I'm working on is for adding students to a course. I have a dropdown menu for the student number (which fetches values from a table), however I'd like to make it so that when the teacher selects the student number from the dropdown menu, that student's name and major appear on a table below. I have pretty much all the code for it however I can't seem to make it work. The way it is right now it shows the head of the table but it doesn't show any lines.
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
Code for my dropdown menu : (works fine)
<label class="control-label" for="number">Student Number</label>
<?php
$sql = "SELECT number FROM students";
$result = $conn->query($sql);
echo "<select class=".'"form-control"'.' id="number" name="number" for="number">';
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['number'] . '">' . $row['number'] . "</option>";
}
echo "</select>";
?>
Code for my table : (shows only head of table, which is the best I got after moving around the code and getting conversion errors and such)
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$sql1 = "SELECT name FROM students WHERE number='$row'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
$sql2 = "SELECT major FROM students where number='$row'";
$result2 = $conn->query($sql2);
$value1 = $result2->fetch_object();
echo "<tr>
<td>".$value."</td>
<td>".$value1."</td>
</tr>";
?>
</tbody>
</table>
Thank you for all your help!!
Before I can formulate a complete answer, I must advise you that there are a few logical errors in your code.
How does your page "know" that a user selected an option from the select? You should perhaps intercept the event and respond to that using an asynchronoys mechanism, e.g. via AJAX.
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
Once you have described how you mean to address issue #1 we can continue discussing the complete solution.
Well, I think there will be no $row in the the second snippet.
It seems that you didn't pass your $row from 1st snippet to 2nd snippet.
You can read this:
PHP Pass variable to next page
You can use session, cookie, get and post.
Or can just simply use "include", then the variables you defined can be used in the second page.
<?php
include "page1.php";
?>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$number = $row['number'];
$sql1 = "SELECT name, major FROM students WHERE number='$number'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
echo "<tr>
<td>".$value['name']."</td>
<td>".$value['major']."</td>
</tr>";
?>
</tbody>
</table>
According to godzillante's answer below, the mysql query should be like this:
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
I notice that you use $row as the key of your second query.
But in the first snippet, the data you fetch is "$row" (it is an array, see PHP - fetch_assoc)
You should use $row['number'] instead.
Being a huge PHP newbie I find myself stuck here.
I have an HTML table for a videogame store filled with elements taken from my database.
The point is, I want to be able to add a link to the game title. Moreover I want the link to direct to some "gamePage.php", a php page used for every videogame but of course showing different infos for each game (title, console etc).
The fact is that not only I can't add the hyperlink, but I have no clue on how to carry the videogame infos when I click on a link (even managing to add the link, all I would manage to do would be redirecting the user to a blank gamePage.php with no title).
This is the code I use to fill the table (the restore function fills my table):
<html>
<body>
<div>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Title</td>
<td>Console</td>
<td>Genre</td>
<td>Price</td>
</tr>
<?php
$conn = #pg_connect('dbname=project user=memyself password=project');
function search(){
<!-- Work in progress -->
}
function restore(){
$query = "SELECT v.Title , c.Consolename , g.Genrename , v.Price
FROM vg_shop.videogame v, vg_shop.console c, vg_shop.genre g
WHERE v.Console=c.IDConsole AND v.Genre=g.IDGenre";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
}
}
<!-- some code -->
</body>
</html>
At first i tried to do this
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
But all I get is a white page, there's some syntax error I don't get.
And, even if it worked, I still can't carry at least the videogame PID through the gamePage link
so, you're managing to go to gamepage.php somehow.
So you need to add some sort of identifier to your link you that you could do some query on the gamepage.php by using that identifier to get info for that particular game.
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td><a href='gamePage.php?id=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['id'], $myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
Note: I assume that you're picking $myrow['id'] from database as well.
now on your gamepage.php do following.
$id = $_GET['id'];
$sql = "SELECT * FROM vg_shop.videogame WHERE `id` = $id";
$result = pg_query($sql);
if($result){
$result = pg_fetch_assoc($result):
//...
// echo "Name: ".$result['Title'];
// other fields
}
$result will have all info about that particular game that was clicked, you can display all as you want.
Cheers :)
Ive got a code running smoothly which shows the list of people who are level 8 as shown below
I want when a person click on the username of the people it redirects them to their profile, actually i've got no clue or ideas of how could that be done. So i need a little bit of help to get some points on this.
Here is the code to show the above output
<?php
$lvl8 = 0;
$content = "";
$query = $koneksi->prepare("SELECT `user`, `level`, `LastOnlineDate` FROM `playerdata` WHERE `banned`=0 AND `level`=8");
$query->execute();
while($data = $query->fetch())
{
$lvl8++;
$content .= "<tr><td>".$lvl8."</td>";
$content .= "<td>".$data['user']."</td>";
$content .= "<td>".$data['LastOnlineDate']."</td></tr>";
}
?>
<table class="table table-bordered">
<thead>
<tr>
<td colspan='6'><h4><small>Level 8 - Trusted Admin (Total <?php echo $lvl8 ?>)</small></h4></td>
</tr>
<td><h5>Number</h5></td>
<td><h5>Username</h5></td>
<td><h5>Last Login</h5></td>
</thead>
<?php
if($query->rowCount() == 0)
{
echo "<tr><td colspan='6'><small>No rows found</small></td></tr>";
}
echo $content;
?>
</table>
first thing you should do is, have an a tag for name, like this
$content .= "<td><a href='link to a new file?id=userid from database'>".$data['user']."</a></td>";
In the new page, you can capture the id of the user, run a query to fetch the details of obtained id and then show the details obtained from database.
Create a http query or post form for your action.
like this in your foreach loop.
GET
<?php echo $username ?>
in your ending script for example a controller in an mvc architecture:
$id = $_GET['user_id'];
// do database stuff and view
Do your query using $id and fetch the result then display your view.
Basically you iterate over user id's to create links that carry the id of the clicked user in order to fetch the selected id.
Im not sure if a similar question has been asked before, but here goes anyway. (I did do a search and found nothing relating to my question).
I am developing a website in which videos are played using the HTML5 video player. I have a connection to my database, a "watch" page that pulls all the correct data using a variable linked to the id (watch.php?v=1). I would like to have an index page where the most recent videos are pulled. They are ordered by the column "id" and everything works when I try and pull one result from the query. How would I go about getting multiple values? Here is my php code (server details hidden):
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
$video = mysqli_fetch_array($result, MYSQLI_ASSOC);
mysqli_close($mysqli);
?>
And here is my HTML code for the table.
<table>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
</table>
That isn't the full code, but once I know the procedure I can apply it where needed!
I'm quite new to php and mysql, I can connect to databases but that's about it so a full walkthrough about what does what would be great!
Many Thanks,
James Wassall
You can iterate in for or while loop by calling mysqli_fetch_array($result, MYSQLI_ASSOC):
<table>
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
while($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
<?php
}
mysqli_close($mysqli);
?>
</table>
Note that you should consider checking error statements, null controls etc.
try this
while($video = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><h2><?php echo $video['title']; ?></h2></td>
</tr>
<?php
}
?>
Each time you call mysqli_fetch_array, only one row is fetched.
You need to do something like
while ($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// output $video['title']
}
(according to: http://www.php.net/manual/en/mysqli-result.fetch-array.php)
Try this,
<table>
<?php while($row = $result->fetch_array(MYSQLI_ASSOC)){ ?>
<tr>
<td><h2><? echo $row['title']; ?></h2></td>
<td><h2><? echo $row['description']; ?></h2></td>
</tr>
<?php } ?>
</table>