Using an incremented value in a SELECT WHERE query MYSQL - php

Let me start off that I have only been coding for the past few months. I know I've probably got a ton of mistakes or bad practices everywhere. I like constructive criticism, so please let me know what i can do better, along with how to address my current issue.
This code's purpose is to create a table of part numbers, and their associated location column data (storage type, Rack number, Shelf number) based on previously entered information. I've got the entry form working perfectly. I type in a number of parts I want to search for, and it posts that number back to itself. I'm then presented with that number of text input fields to put in part numbers.
//this form is to submit the number of parts you're looking for,
//and posts back to itself
<form action=View2.php method="post">
<input type="text" name="num">
<button type="submit">Number of Parts</button>
</form>
//This form takes the posted number, and creates that many text fields,
//populated with the number part you are entering.
<form action="List.php" method="post">
<?php while ($i<=$num){
echo "<input type='text' name='part$i' value='part$i'><br><br>";$i++;}?><input type="hidden" name="num" value="<?php $num?>">
<button type="submit">Submit</button>
</form>
My problem comes with running a mysqli_query to populate the table. I'm stuck as to where to go from here. I know that i need to take each part number that gets posted, and use it as the criteria in a SELECT WHERE search, so i made this While loop:
<?php
echo "<table border='1'>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Rack</th>
<th>Shelf</th>
</tr>";
while($i<=$num){
$x=$_POST["part$i"];
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
$row = ($result);
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['rcb'] . "</td>";
echo "<td>" . $row['ra'] . "</td>";
echo "<td>" . $row['sh'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";?>
The page crashes at this point, but if i comment out the $result line, i'll get the table with the part number fields populated with the values from the previous page.
Anyone have any idea what i'm doing wrong, or how i can do it better?

This line doesn't do anything good :
$result = ($con,"SELECT * FROM parts WHERE pn ='$x'");
You need to actually query the DB.
$mysqli = new mysqli("localhost", "my_user", "my_password", "...");
...
$result = $mysqli->query("SELECT * FROM parts WHERE pn ='$x'");
You should use prepared statements so your code isn't open to sql injections though...

Related

Multiple actions for a single form

I have an html homepage which has a form. The form submit button sends the query to a single php page called First.php which gives the necessary data from the database in a tabular format. A single column from the table contains links as the contents of the column are too large to display on the same page. Once the link is selected, it gives the exact column information of only that query which I submitted on the homepage.
My general idea was to give two actions to the form action which can be used on two different pages but that to no result.
Here's the homepage :
<form action="First.php" action ="Second.php" method="POST">
<input type="text" size="90" name="search1">
<input type="hidden" size="90" name="search1">
<input type="submit" name="submit" value="Search..">
</form>
First.php after connecting to database and the firing the sql query :
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='Second.php'>Link</b></td>";
echo "</tr>";
}
}
Please do help me for the Second.php.
Any help would be deeply appreciated.
Thank you!
This is common pagination problem. You should use extra parameter in your form.
do something like
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='First.php?page=2'>Link</b></td>";
echo "</tr>";
}
}
You do not need a second action at all (and you cannot have one). What you need is to pass the id of the row to Second.php as a GET parameter. If you are not familiar with the concept, look it up because you will need it. A lot.
In Second.php you do not need the search parameters anymore because you are showing the details about a single row and you have its id. You just make a query to the DB to retrieve it by id and the old search becomes irrelevant.
In good conscience I have to say that the mysql_-something functions are a BAD idea. They have been removed in newer versions of php and are dangerous to use in the old ones. I strongly suggest that you use PDO and prepared statements ot at least the mysqli_ family of functions.

MySQL and PHP - make href remember previous variable

I am quite new to PHP, but come with some knowledge of JavaScript.
I am trying to construct a MySQL table which has sortable columns by header, which I managed figure out through looking around the web, etc; but then wanted the SQL query to use a WHERE clause which only shows rows that meet that clause (and it works), but the problem is that when I then sort the columns it goes back to the original value of the $catergory variable.
I hope that makes sense.
Could somebody please tell me what I am doing wrong and either if I need to change the SQL query or find a way to get the PHP to remember the reassigned value of $catergory, when I want to sort the columns afterwards?
Here is my code:
<?php
// Create connection
$con = mysqli_connect("host","user","password","database") or die("Some error occurred during connection " . mysqli_error($con));
$categoryFilter = array('boardroom', 'staffroom', 'kitchen');
$category = 'boardroom';
if (isset($_GET['categoryFilter']) && in_array($_GET['categoryFilter'], $categoryFilter)) {
$category = $_GET['categoryFilter'];
}
$orderBy = array('Image', 'Description', 'Light', 'Room');
$order = 'Image';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
?>
<div class="catbuttons">
<ul>
<li>Boardroom</li>
<li style="height: 17px">Staffroom</li>
<li>Kitchen</li>
</ul>
</div>
<div class="index">
<table border='1'>
<tr>
<th>Image</th>
<th>Description</th>
<th>Light</th>
<th>Room</th>
</tr>
<?php
$result = mysqli_query($con,"SELECT * FROM officeindex WHERE Room='".$category."' ORDER BY ".$order)
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" , $row['Image'] , "</td>";
echo "<td>" , $row['Description'] , "</td>";
echo "<td><img src='" , $row['Light'] , "'></td>";
echo "<td>" , $row['Room'] , "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
Thank you everyone, I have implemented your suggested solutions to my original question and changed the code above, but I am now having further difficulty. The purpose of my code is to construct an interactive product list of sorts. Now that I have the categories (thanks for pointing out the spelling mistake) working, I want the table, at first, to show all the categories, i.e. all the products in the list, before the user clicks on a specific category.
The other problem is that I can't work out what to do about cells which contain multiple categories (Some products fall into multiple categories).
I've thought about using arrays or loops or booleans or some kind to do both of the above, but my knowledge is limited to JavaScript and I'm a bit lost in PHP, even though there are similarities. Please forgive my ignorance.
I hope I have explained this clearly
Could anyone help me please?
The links in your tableheader only contain the orderBy parameter. If you want to keep the categoryFilter, you need to include it in the href of your headers.
For example:
<tr>
<th>Image</th>
<th>Description</th>
<th>Light</th>
<th>Room</th>
</tr>
For the category filter it's the other way around of course:
<li>Boardroom</li>
<li>Staffroom</li>
<li>Kitchen</li>
Also, as #K.K.Smith pointed out, you might want to replace catergory with category
In your links, You have to put the varaibles if they exists.
Example :
<a href="?categoryFilter=staffroom<?php if isset($_GET['orderBy'] echo '&orderBy=", $_GET['orderBy'];?>" />

PHP, MYSQL noob joining(?) tables specifics

I am new to PHP and am making a social network as practice and to apply what I have learned in the "real world". Anyhow, I have two tables in a MySQL database that i am trying to display on my site in the same html table that is being rendered through an php echo.
here are the tables
(table1)
note_system:
-id,
-username,
-note
(table2)
comments:
-id,
-cid (equals id from note_system),
-username,
-comment
so someone makes a post and it saves to the note_system table then someone comments on the post and it saves to the comment table with the id from the note_system table so a relation can be established.
So what I am trying to do is get the post comments to display with the relevant post. I have gathered that I need maybe a JOIN or UNION to make this happen but I am at a complete loss on how to do it. Been racking my brain and doing tons of google searches but I am not really getting anywhere. Everything I try gives me errors. The Notes display just fine and as intended but I can't for the life of me figure out how to get the comments to show up there too.
Here is my code (don't laugh at the noob-ness of my PHP, this is my 2nd PHP program ever and I obviously have much to learn, I would like to clean it up at some point but for now I just want it to be functional)
<?php
// Display Note_Wire
$con=mysqli_connect($host,$username,$password,$dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//format and display the Note_Wire results with comments
$result = mysqli_query($con,"SELECT * FROM note_system");
while($row = mysqli_fetch_array($result))
{
echo "<center>";
echo "<table class='note_wire'>";
echo "<tr>";
echo "<td>" . $row['username'] . "</td>" ;
echo "</tr><tr>";
echo "<td><a href=''>vote up</a>" . " " . $row['rank'] . " " . "<a href=''>vote down</a></td>" ;
echo "</tr><tr>";
echo "<td> <a href='{$row['link']}' target='blank'>{$row['link']}</a>";
echo "</tr><tr>";
echo "<td>" . $row['note'] . "</td>" ;
echo "</tr> ";
//add comments attempt this is where I would like the comments to be displayed
echo '
<td><form action="add_comment.php" method="POST">
<input type="hidden" name="username" value="';
echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
echo '" />';
echo '<input type="hidden" name="cid" value="';
echo $row['id'];
echo '" />';
echo '<textarea name="comment">comment...</textarea></td></tr>
<tr><td><input type="submit" value="comment" />
</form></td></tr>
';
echo "</table>";
// break before next note-wire record renders
echo "<br />";
}
echo "</center>";
?>
I hope my chicken scratch programming makes sense. Thanks for your time and knowledge.
Really the comments are a different data set from the actual post you could just use a second query to get all of the comments related to the post. But table joins are very useful and you should learn them. In this case you would join the note_system and comments table on the shared ID (the foreign key).
So like so:
SELECT *
FROM note_system
LEFT JOIN comments ON comments.cid=note_system.id
This is a literal joining of the tables so your output will include all columsn from both tables as long as there is a match for the joining expression. If there isn't a CID column in the comments table that matches then the values for those columns will be NULL in your output. (If you wanted to only return rows where there is a match you could use an INNER join as opposed to the LEFT OUTER join I've used above.)
This is a good page explaining SQL table joins.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST,DBNAME
$conn = new mysqli('database_server','database_username','database_password','database_name');
SECOND : Create a Query(you may insert your query here)..
$result= $conn->query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = $result->fetch_assoc()){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
for your query try to use this one or either create a relative one.
SELECT 'enter column needed here with their specific database allias ex. TABLE1.ID'FROM NOTE_SYSTEM TABLE1 LEFT JOIN COMMENTS TABLE2 ON TABLE1.ID = TABLE2.CID;

Deletion of rows from populated table

I'm currently facing a strange issue whereby I did not get any errors from my debugging page. My table consists of several rows and only the first row of the table can't be deleted.
Sample form:
$DB = new PDO('sqlite:database/Sample.db');
$result = $DB->query("select * from staff");
foreach ($result as $row)
{
$StaffNo= $row['StaffNo'];
$Name= $row['Name'];
$TelNo= $row ['TelNo'];
echo "<tr>";
//Go to remove.php to remove
echo "<form action=\"Remove.php\" method=\"post\">";
echo "<input type=\"hidden\" name=\"StaffNo\" value=\"$StaffNo\">";
echo "<input type=\"submit\" onclick=\"return confirm('Yes/No')\"/>";
echo "</form>";
echo "</td>";
echo '<td data-column-name="Name" char="data">'.$Name.'</td>';
echo '<td data-column-name="TelNo" char="data">'.$TelNo.'</td>';
</tr>
}
Remove.php:
$StaffNo= $_POST["StaffNo"];
$DB = new PDO('sqlite:database/Sample.db');
$DB->query("DELETE FROM Staff WHERE StaffNo=".$StaffNo);
#header("location:view.php");
From my code above, I can delete all my sample records except for the first row. It doesn't get deleted... Kindly advise if i did wrong somewhere....
I've tried your code and apart from the broken table code, everything seems fine. Make sure your table is correct (<table><tr><td>Content</td></tr></table>). In your question, you're missing an opening <td> on line 9 of the first file, as well as missing <table> tags. Some browsers don't handle broken tables very well and that might mess up your form.
Your query will also break if $StaffNo is an empty string, so double check that.
You can also try removing the header() call and print out errors using $DB->errorInfo().
To inject your variable i the hidden field you should type
".$StaffNo."
instead of
"$StaffNo".
probably it doesn't delete the first row of your table becouse it's the only one with a StaffNo defined.

Can't delete a user from database by clicking delete button on the same page

I searched fot the solution but nothing works.
<?php
$result = mysql_query("SELECT username, EmailAddress FROM users", $connection);
echo "<form method='post'><table class='mecz' cellpadding='0' cellspacing='0' border='0'>
<tr>
<th>user names:</th>
<th>address e-mail</th>
<th></th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr align='center'>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['EmailAddress'] . "</td>";
echo "<td><input class='delete' type='submit' name='delete' value='usuĊ„' /></td>";
echo "</tr>";
}
echo "</table></form>";
//here a part when i'm trying to pass delete action from the form
?>
<?php
if (($_POST['username'] != "") && (isset($_POST['delete'])))
{
$username = $_POST['username'];
$query = "DELETE FROM users WHERE username = '".$username."' AND '".$_POST['delete']."'";
$result = mysql_query($query,$connection);
echo mysql_error();
}
?>
I think the solution is not very complex but i can't find it, please help.
Thanks,
Kris
you aren't sending username in the code you posted, so $_POST['username'] isn't set and thus the delete isn't executed.
even if you would enter the if-block, your delete-query doesn't make much sense - what should AND '".$_POST['delete']."' do? that part seems pretty sensless.
you try to make one form containing several submit-buttons (one for every user). on server-side you can't determine wich submit-button is pressed as the whole form gets sent as one big bunch of data. you'll need one form per user or simply use links (a-elements) to sent the delete- and username-values (but note that in the latter case you'd do GET instead of POST-requests)
you don't specify a action for your form - this might or might not be a problem in your case, please see the various comments to your question about this for more information.
your delete-query is perfectly open for sql-injections. please consider using prepared statements or at least mysql_real_escape_sting to avoid this.
and this are only the real problematic points that prevent your code from working at all or leave awkward security-holes. in addition, there are some things that are just unneccessary or some kind of messy (like calling mysql_error every time instead of doing that only if a query fails - but maybe you just added that for debugging).
altogether it seems like you should start reading a good book or some detailed tutoriala again to refresh and extend your fundamental understanding of php/mysql/html.

Categories