I'm totally stuck! I need to create navigation buttons in order to go through records that match a specific Id. So far I have only been able to retrieve 1 record (the first one). I am using the following code to do so:
$query = "SELECT t1.requester_name, t1.requester_email, t1.client_name, t1.client_country, t1.machine_quantity, t1.severity, t1.sales_connect, t1.request_status, t2.serial_type, t2.serial_model, t2.serial_number, t2.machine_status, t2.machine_config, t2.brand, t2.tier, t2.request_id
FROM requests t1
LEFT JOIN serialnumbers t2
ON t1.request_id = t2.request_id
WHERE t1.request_id = {$id} ";
$results = mysql_query($query, $connection);
$row = mysql_fetch_assoc($results);
The records are coming from 2 distinct tables and while I am having no trouble with the Request Table (Always one row), I cannot manage to figure out how to get every row in the Serial Numbers table (one to many relationship).
I am using a html form to display these values... Here is a sample of how I am doing so:
<input type="text" value="<?php echo $row['serial_type']; ?>" id="machineType" name="machineType[]" />
Any ideas on how I can achieve this objective?
you are going to want to make your $row = mysql_fetch_assoc a while loop.
while ($row = mysql_fetch_assoc($results)){
echo '<input type="text" value="'.$row['serial-type']." id="machineType" name="machineType[]" />';
}
something along those lines.
Related
I'd like to search 3 separate tables I've created from 1 form and return the data in alphabetical order. Currently I can search 3 tables separately with use of a drop-down box (from my form) to select a table but I've fallen short at querying them simultaneously and returning all the data in alphabetical order. I've been trying to solve it but I'm struggling a lot.
Currently what my program searches through separate tables for what the user previously input into my form. Now I would like to be able to search through all my tables in 1 go and return the information in alphabetical order, meaning some values from tables might be spread out.
I have 3 tables: "Insecttable", "birdtable" and "butterflytable"
There are 3 controllers: "ControllerInsectTable", ControllerBirdTable and "ControllerButterflyTable"
I'm trying to make another controller: "ControllerAllTables" that can search through all tables.
HTML:
<form name="searchForm" id="searchForm" method="POST" action="ControllerAllTables.php">
Search for: <input type="text" name="aSearch">
<input type="submit" name="searchButton" value="Search">
</form>
PHP:
// Collect Data
// If an input has been given
if(isset($_POST["aSearch"])) {
$searchq = $_POST["aSearch"];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq); //Can only search words
// Select statements if keywords match
$sql = "SELECT * FROM insecttable WHERE insectName LIKE '%$searchq%'";
$sql1 = "SELECT * FROM butterflytable WHERE butterflyName LIKE '%$searchq%'";
$sql2 = "SELECT * FROM birdtable WHERE birdName LIKE '%$searchq%'";
}
// Tests if the code been inserted
if ($conn->query($sql && $sql1 &&sql2)=== TRUE){
echo "The rows you have searched for are:";
} else {
echo "Connection failed: ";
echo $conn->error;
}
// Show fields
$result = $conn->query($sql && $sql1 &&sql2);
// Output data of each row
if ($result-> num_rows> 0) {
readfile("ViewReturn.html");
while($row = $result-> fetch_assoc()) {
// echo "ID: ".$row["id"]. "<br>";
echo "Insect: ".$row["insectName"]. "<br><br>";
echo "Bird: ".$row["birdName"]. "<br><br>";
echo "Butterfly: ".$row["butterflyName"]. "<br><br>";
}
} else {
echo "0 results";
}
I cut out some of the bits of my code that didn't affect my question, like making connections and such.
At the moment, I have no idea how to return values in order, and I'm seriously stuck at searching multiple tables from one query. I've looked at "joins" but I really don;'t understand them.
As you can tell I'm not very good at PHP, and I hope I can soon rid it from my life. I've been completely unsuccessful in this section of my program and I'm looking for help and criticism. I know it's a lot to ask but I'm really stuck, thanks.
You'll want to use the UNION operator to combine the query results, being sure to order the data after it has been combined. This can affect performance, but hopefully your result sets aren't too large.
SELECT name -- because we NEVER use select *
FROM
(
SELECT insectName AS name FROM InsectTable WHERE insectName LIKE '$searchq%'
UNION ALL
SELECT butterflyName AS name FROM ButterflyTable WHERE butterflyName LIKE '$searchq%'
UNION ALL
SELECT birdName AS name FROM BirdTable WHERE birdName LIKE '$searchq%'
)
Also, you might want to consider a redesign of the database. If the items in your tables are all related then they are effectively a super class. If you Google "SQL super class design" you should be able to find some good patterns for this.
Also, appending the word "Table" to the end of all of your table names is not something that is usually done. If your table holds data about insects then it's "Insect" or "Insects" (I'll ignore the singular/plural debate for now). The fact that it's a table is already self-evident.
I'm trying to create a simple topic and posting system and I have two tables in a MySQL database; a topics table and a posts table. In my posts table I have a post_parentID field that links to a topic_id field in my topics table.
Here is how I start my query selecting (and displaying) all the topics that are in the topic table. I then save the topic_id field into a variable:
<?php
$sql = "SELECT * FROM topics INNER JOIN members ON topics.topic_by = members.id";
$topics = $mysqli->query($sql);
if ($topics->num_rows > 0) {
// output data of each topic
while($row = $topics->fetch_assoc()) {
//Saving TopicID into variable
$topic_id = $row["topic_id"];
$_SESSION['topicid'] = $topic_id;?>
Right after I display the html for each topic, I start a new while loop to display each post within each topic:
<?php
$sql = "SELECT * FROM posts INNER JOIN members ON posts.post_by = members.id WHERE post_parentID = $topic_id";
$posts = $mysqli->query($sql);
if ($posts->num_rows > 0) {
// output data of each post
while($row = $posts->fetch_assoc()) { ?>
Right after this, I display the html for each post and then I display the form-control to enter a post, which is directed to a send_post.php file:
<div class="chat-message-form">
<div class="form-group">
<form action="includes/send_post.php" method="post">
<textarea class="form-control message-input" name="post_content" placeholder="Enter message text"></textarea>
<input type="submit">
</form>
</div>
</div>
When I call $topic_id in my send_post.php file like this:
$topic_id = $_SESSION['topicid'];
It only returns the very last topic_id in my topics table instead of the current topic_id in the while loop. Is my logic about this right or should I be doing something different?
By doing this in your loop:
$_SESSION['topicid'] = $topic_id;
you're overwriting the value of topicid everytime you loop. I don't know how exactly you want your topicid to look like but a possible way to avoid this would be:
$_SESSION['topicid'] = array();
while($row = $topics->fetch_assoc()) {
$_SESSION['topicid'][] = $topic_id;
...
Another easy way to the this is:
">to your next page // this will attach specific ids to each link during loop
Afterwards, go to your next page and use the $_GET method to get the id send via url...then apply it to ur query there
$topic_id= 0 //set this before the loop
while(){...
.....
$topic_id++; //increment id by one for each loop
echo $topic_id // if you want to print the values of the id
to your next page // concatenate specific id to selected link
}// close while loop
in your nextpage.php
$variable_name=$_GET['$topic_id'];// this way you get the specific id concatenated to the particular link clicked
I have 2 tables, comments and gossips.
Gossips has 3 columns: id, userid, gossip.
Comments has 4 columns: id, userid, gossipid, comment.
I wrote this code so that the program echos all the gossips and the comments specific to each gossip.
$query = 'SELECT * FROM gossips ORDER BY id DESC LIMIT 0,10';
$result = mysqli_query($cxn, $query)
or die("Couldn't execute query");
while($row = mysqli_fetch_assoc($result))
{
echo '<div class="gossip">'.$row['gossip'].'</div><form action="comment.php" method="post"><input type="hidden" name="gossipid" value="'.$row['id'].'" />';
echo '<input type="text" name="comment" placeholder="Write your comment here"/><br /><input type="submit" value="Comment" /></form><br />';
$querycomment = "SELECT * FROM comment WHERE gossipid ='{$row['id']}' ORDER BY id DESC";
$resultcomment = mysqli_query($cxn, $query)
or die("Couldn't fetch comments.");
while($comments = mysqli_fetch_assoc($resultcomment))
{
echo $comments['comment'];
}
}
The output of this code is only echoing the gossips and isn't executing the second while loop. What could be the problem ?
You go through the entire $resultcomment result set the first time you go around that loop. When the SECOND iteration of the outer $result loop starts up, there's no more data to be fetched from that second query, so in effect the inner loop only ever runs for that FIRST record from the $result set.
Since you seem to be filtering the inner loop's results using the outer loop's data, why not base that inner query on the same data, so you don't suck across your entire comment table and throw away everything EXCEPT for the matching records? That's a hideous waste.
Something more like
SELECT * FROM gossips
while(fetch gossip) {
SELECT * FROM comment WHERE id = gossip.id
}
This is somewhat more efficient, since you fetch only the comments you'd actually want to display. A further optimization would be to rewrite both queries as a single JOIN query, with some looping logic to detect when you change between gossips.
I have 2 tables, comments and gossips.
Gossips has 3 columns: id, userid, gossip.
Comments has 4 columns: id, userid, gossipid, comment.
I wrote this code so that the program echos all the gossips and the comments specific to each gossip.
$query = 'SELECT * FROM gossips ORDER BY id DESC LIMIT 0,10';
$result = mysqli_query($cxn, $query)
or die("Couldn't execute query");
while($row = mysqli_fetch_assoc($result))
{
echo '<div class="gossip">'.$row['gossip'].'</div><form action="comment.php" method="post"><input type="hidden" name="gossipid" value="'.$row['id'].'" />';
echo '<input type="text" name="comment" placeholder="Write your comment here"/><br /><input type="submit" value="Comment" /></form><br />';
$querycomment = "SELECT * FROM comment WHERE gossipid ='{$row['id']}' ORDER BY id DESC";
$resultcomment = mysqli_query($cxn, $query)
or die("Couldn't fetch comments.");
while($comments = mysqli_fetch_assoc($resultcomment))
{
echo $comments['comment'];
}
}
The output of this code is only echoing the gossips and isn't executing the second while loop. What could be the problem ?
You go through the entire $resultcomment result set the first time you go around that loop. When the SECOND iteration of the outer $result loop starts up, there's no more data to be fetched from that second query, so in effect the inner loop only ever runs for that FIRST record from the $result set.
Since you seem to be filtering the inner loop's results using the outer loop's data, why not base that inner query on the same data, so you don't suck across your entire comment table and throw away everything EXCEPT for the matching records? That's a hideous waste.
Something more like
SELECT * FROM gossips
while(fetch gossip) {
SELECT * FROM comment WHERE id = gossip.id
}
This is somewhat more efficient, since you fetch only the comments you'd actually want to display. A further optimization would be to rewrite both queries as a single JOIN query, with some looping logic to detect when you change between gossips.
I hope my title says something about what I am trying to do, I'll try to describe it a bit better:
I have a database with two tables, one named "movies" and another one named "directors".
Its a small movie database where we are supposed to be able to display all the movies, their title, year and producer.
In the table "directors" I have a field "id" and in my "movies" table i have a field named "producer" with the matching id. I want the while loop to loop thru all the movies in the "movies" table (working fine) and if i choose to print the "id" from "movies" its correct.
But now i want the loop to display the "title" and "year" from the "movies" table, and go to the "directors" table and get the name for the matching "id".
I'm new to both PHP and mysql queries and my code does this correctly for the first movie, but the rest have their "producer" field empty as for now.
(Right now I'm just trying to display the surname to see that it works).
FYI this is for a school project.
Code:
<?php
$sql = "SELECT * FROM movies ORDER BY title ASC";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"title");
$year=mysql_result($result,$i,"year");
$producer=mysql_result($result,$i,"producer");
$id=mysql_result($result,$i,"id");
$sqldir = "SELECT * FROM directors WHERE id='$producer'";
$result1 = mysql_query($sqldir);
$row1 = mysql_fetch_assoc($result1);
$iddir = $row['id'];
$producertext = mysql_result($result1,$i,"surname");
?>
<b>Title:</b> <?php echo $title ?>
<br/><b>Year:</b> <?php echo $year ?>
<br/><b>Director:</b> <?php echo $producertext ?>
<br/>
</form> <HR>
<?php
$i++;
}
?>
Assuming that every movie has a single director then you can just create a joined query
SELECT movies.title as title, movies.year as `year` producer.surname as surname
FROM movies, producer where movies.producter = producer.id ORDER BY title ASC
You can then just walk the result set and the surname will be in the result arrays.
Here should be a complete solution assuming the query works as expected
<?php
$sql = "SELECT movies.title as title, movies.year as `year` producer.surname as surname FROM movies, producer where movies.producter = producer.id ORDER BY title ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)): ?>
<b>Title:</b> <?php echo $row['title'] ?>
<br/><b>Year:</b> <?php echo $row['year'] ?>
<br/><b>Director:</b> <?php echo $row['surname]; ?>
<?php
endwhile;
?>
You are using wrong function
$num=mysql_numrows($result);
you should use
$num=mysql_num_rows($result);
You're accessing the producer information as:
$producertext = mysql_result($result1,$i,"surname");
However, $i is the index from the main SQL loop; so on the second run through, you'll be looking for the surname from the second line of your producer result set, which won't necessarily be there. So only the first producer is showing up.
Some other things you might want to look at - you can use PDO or mysqli to access data - they're more secure that mysql, which is in the process of being deprecated. You're also using mysql_fetch_assoc at the moment, but you don't seem to be using the resulting array for anything. It's a lot more common to go through a result set with something like:
while ($row = myssql_fetch_assoc($result)) {
....
}
Which loads the next row into an associative array for you to use, and stops when you run out of rows.
Also, have you considered what your code should do if there's more than one producer for a film? You might want to add a loop for that query, too.