Mysql select query using value from a php dropdown - php

I started programming in php and I'm having a small doubt.
I'm trying to do a search the database using a value from a dropdown.
The problem is that the query always uses the last value of the dropdown.
Does anyone can help me find the error?
Why is research in where clause is always the last value of the dropdown?
Code
<tr><td>Technical:</td><td>
<select>
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
$id=$row["idTechnical"];
$thing=$row["name"];
echo "<OPTION VALUE=$id>$thing</option>";
}
?>
</select>
<?php
if (isset($_POST['Next'])) {
if($_REQUEST['Next']=='Search') {
{
$sql="select idTask, descTask, deadline, idTechnical from tasks where idTechnical = '$id' order by deadline desc";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
}
}
}
?>
I select any value from dropdown, but only uses the last value in clause where :S

Here is what I would do for the form (assuming you have a proper form tag with an action attribute that points to the correct PHP script):
<tr>
<td>Technical:</td>
<td>
<select name="technical">
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
echo '<option value='.$row["idTechnical"].'>
'.$row["name"].'
</option>';
}
?>
</select>
</td>
Then in the PHP script:
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = '.$_REQUEST['technical'].'
ORDER BY deadline DESC';
$result=mysql_query($sql);
$count=mysql_num_rows($result);
This should do it for you.
But please note: The script above is a security risk because it leaves the door wide open for SQL injection
A better way to do this would be to use a PDO Prepared statement, like this:
$db = new PDO('mysql:host=CHANGE_THIS_TO_YOUR_HOST_NAME;
dbname=CHANGE_THIS_TO_YOUR_DATABASE',
'CHANGE_THIS_TO_YOUR_USERNAME',
'CHANGE_THIS_TO_YOUR_PASSWORD');
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = :id
ORDER BY deadline DESC';
$query = $db->prepare($sql);
$query->bindValue(':id', $_REQUEST['technical']);
$query->execute();
$count = $query->rowCount();
If you're just starting in PHP, I would highly recommend that you spend some time to become familiar with PDO Database querying. Good luck and happy coding!

Related

PHP mySQL Sort post by date

I'm trying to create a website where anyone can post anything to it without creating an account, long as its just text. My problem is because every time I start the website and post something. Its sent to the bottom, where oldest posts are at the top and new posts are sent to the top. I want to see the new posts on top instead. This is my first time working with PHP, mySQL and databases in general so my code might look bad. Tell me if more information / code is needed. Thank you for your time.
<?php
function setPosts($conn){
if(isset($_POST['postSubmit'])){
$pid = $_POST['pid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql= "INSERT INTO post(pid, date ,message) VALUES ('$pid', '$date', '$message');";
$result = mysqli_query($conn, $sql);
}
}
function getPosts($conn){
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
You need to add "ORDER BY" to your "SELECT" to sort it.
$sql = "SELECT * FROM post ORDER BY date DESC";
The "DESC" is there so that new posts will be on top. We'd use "ASC" if we wanted older posts on top.
You need to use ODRER BY clause like below :-
$sql = "SELECT * FROM post ORDER BY date DESC";
Reference:- ODRER BY clause
Note:- Your insersion code is wide open for SQL Injection. Use mysqli prepared statements to prevent from it.
Reference:- mysqli::prepare
You need to sort mysql result by date and order it in descending order.replace mysql query to this
$sql = "SELECT * FROM post SORT BY date order BY DESC";
function getPosts($conn){
$sql = "SELECT date,message FROM post ORDER BY date DESC";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}

Select id from one query and use it in another

I have this code. In the first query I want it to select a pid. Then I want to somehow use the selected pid as WHERE in the second query. This do not work but I want it to work on this(the same) page. I have read about this on other forums but I still didn't fix it. Probably a small mistake somewhere.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$loggedInUserId = $_SESSION['user_id'];
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
//$type= "Content-type:".$row['image_type'];
//header ($type);
echo "<form action='respodents.php' method='post'><button name='submit' id='projectbutton'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100px height=100px/>"." <div id='project_name'>".$row['project_name']."</div>"."
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
</div>
</button></form>";
}}
mysqli_close($mysqli);
?>
With respect to the sql, perhaps this might work
SELECT `pid`, `project_name`, `image`, `image_type`
FROM `project` WHERE `pid` = (
SELECT `pid` FROM `users` WHERE `id`='$loggedInUserId'
);
The original code had a mix of mysql and mysqli functions with a further mix of Object Orientated and Procedural method calls. Whilst this wouldn't cause an error necessarily it is bad practise to do so. Below is all in a procedural style - it's not tested but it incorporates the two queries into one which should work ( famous last words )
Sidenote: That said - with mysqli you can take advantage of prepared statements which help mitigate against the threat of sql injection - it's quite straightforward to lean and use - so rather than embedding a variable in the sql you would use a placeholder and then bind a variable to that.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
/* db connection? */
if( mysqli_connect_errno() ) echo mysqli_connect_error();
else {
$loggedInUserId = $_SESSION['user_id'];
$sql="select `pid`, `project_name`, `image`, `image_type`
from `project`
where `pid` = (
select `pid` from `users` where `id`='$loggedinuserid'
);";
$resu=mysqli_query( $mysqli, $sql );
if( $resu ){
$ro = mysqli_fetch_row( $resu );
while( $row=mysqli_fetch_object( $resu ) ){
echo "<form action='respodents.php' method='post'>
<button name='submit' id='projectbutton'><!-- you cannot re-use IDs, they MUST be unique! -->
<div>
<img src'=pic.php?pid=".$row->pid."' width='100px' height='100px'/>
<div id='project_name'>".$row->project_name."</div><!-- you cannot re-use IDs, they MUST be unique! -->
<input type='hidden' name='pid' value='".$row->pid."'/>
<input type='hidden' name='project_name' value='".$row->project_name."'/>
</div>
</button>
</form>";
}
}
mysqli_close( $mysqli );
}
?>
First of all, you should not be mixing mysql and mysqli. Let's use mysqli as mysql is deprecated.
I will assume that you don't need it to be in just one query since you never specified.
$result = mysqli_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
while($row = mysqli_fetch_row($result))
{
$pid = $row['pid'];
}
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $pid. "';";
$result = $mysqli->query($sql);
Also, you really should learn to use prepared statements as they are a much safer.
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='".
$row["pid"]. "';";
$ro = mysql_fetch_row($resu); should be spelled $row not $ro. There's nothing in the variable you are calling in your SQL statement.
Also, your SQL Statement doesn't make much sense in terms of
$row["pid"],
you are accessing a numerical array with mysql_fetch_row(http://php.net/manual/en/function.mysql-fetch-row.php).
If anything, you want to do mysql_fetch_array or mysql_fetch_assoc, to fetch an associative array that you can access the "pid" data statement. The way you are doing it with fetch_row you want to access it numerical, i.e.,
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
The above is copied directly from the php mysql_fetch_row docs.
Edit::
http://php.net/manual/en/mysqli-result.fetch-row.php
Mysqli Docs for fetch_row.
I believe you have to change this code:
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
to:
$resu = mysql_query("SELECT pid FROM users WHERE id='".$loggedInUserId."'");
And do not mix mysql and mysqli commands you can easly mess up you code that way.
This looks smelly
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";
change $ro = mysql_fetch_row($resu); to $row = mysql_fetch_row($resu);

PHP MySQL query result into a variable and then echo ($variable)

wish to check the last id (cat_id) in a table (category) and insert that result into a variable that I can echo.
My intention is to create a record last cat_id +1 as long as it doesnt already exist of course.
What I thought I should do was something like this;
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
echo ($result);
?>
But oh no, nothing so simple. The echo was only to check I had the correct result (in phpmyadmin it returns the desired number)
Then I was hoping to be able to, with a simple html form, was to ask if the user wanted to add a category through a text box:
addrec.html:
<form action="addrec.php" method="post">
Category: <input type="text" name="category">
<input type="submit">
</form>
addrec.php:
<?php
require "mydbdetails.php";
$new_id = $result + 1;
$query="INSERT INTO category VALUES ($new_id, 'Fruits')";
?>
You must first know as a developer, that mysql extension in php will be fully deprecated in the future as it is already in the newer php versions. So use instead Mysqli extension and PDO for sanitation and securer code for your database.
As it goes to your question:- Try the following ;
// Make a MySQL Connection
$query = "SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
//assign result to a variable
$result = mysql_query($query) or die(mysql_error());
//fetch result as an associative array
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['cat_id'];
You can assign it to avariable $row['cat_id'] = $catId; like that and use it .
echo $result[0]['cat_id'] i think
Please consider using PDO query Syntax instead of the old deprecated mysql_query.
If you make a PDO connection and store it in the $conn object ( pretty similar to what you already have in mydbdetails.php) just do:
$query=$conn->query("SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1");
$result=$query->fetchAll(PDO::FETCH_COLUMN,0);
echo ($result[0]);
First of all, you should really be using mysqli instead of mysql because mysql is deprecated and will be removed in PHP 5.5.
Of course the PDO would be better, but i think that you're so new that it would be a bit to much right now.
Basically, you're firing a Query, but you don't tell the query to what connection. You're doing this:
$result=mysql_query($query);
What it should be is
$result=mysqli_query($link, $query);
Where $link is the variable where you're setting up the database connection in the mydbdetails.php file.
Without the connection the Query doesn't know where to get the data from.
But if OOP isn't new to you, the answer from #amenadiel is better because it's an OOP way.
Further, there is no need for your $new_id = $result + 1; line.
IDs should almost always set to Auto Increament in the database, so this line will be done automatically in the database when you're adding a new dataset.
More information here
Hope this helps
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
$i;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
var_dump($row); /* dump rows*/
/* or add to array to use later */
$results[$i] = $row; // add to array
$i++; // +1 the counter to increment the array
}
?>
Try to write your scripts in mysqli_ or pdo functions. Work around in mysql_ function (not recommended)
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$cat_id = $row['cat_id'] + 1;
} else {
$cat_id = 1;
}
?>
cat_is is the primary key? If yes you can set that column as auto increment. You can try this
https://php.net/manual/en/function.mysql-result.php

compare and hide in drop

I have a drop downmenu on a page, after users add a content to the db,
i do not want the specific value that was added
from the dorpdown menu to show in the list again.
I do not want to delete that specific value from the dropdown table.
Your help will do.
Here is my code below:
<?php
$query = "SELECT * FROM vreg_no order by vreg desc";
$rs = mysql_query($query);
while($row = mysql_fetch_assoc($rs))
{{
$_SESSION['svregx'] = $row['vreg'];
}}
?>
<select name="svreg" class="bodytxt" id="svreg">
<option>Select Vehicle #</option>
<?php
$query = "SELECT * FROM vreg_no order by vreg desc";
$rs = mysql_query($query);
while($row = mysql_fetch_assoc($rs))
{{
$vreg = $row['vreg'];
if($_SESSION['svregx'] == $vreg){
//do nothing
}
elseif($_SESSION['svregx'] != $vreg){
echo"<option value='$vreg'>$vreg</option>";
}else{}
}}
?>
</select>
You are executing the same query twice.
The first one should be something like:
$query = "SELECT * FROM vreg_no WHERE user_id = YOUR_USER_ID";
or probably a join depending on your database structure.
Than you can add all values to an array and use something like in_array to check if this value exists for a certain user.
And you should dump the deprecated mysql_* functions and switch to prepared statements with bound variables in PDO or mysqli.
If the issue is not producing duplicate user generated content, wouldn't it just be an issue of issuing a DISTINCT query?
$query = "SELECT DISTINCT vreg FROM vreg_no order by vreg desc";

Question if my code is a low resources one

Hi please tell me if this is a low resources piece of code, and if it is not how shall I change it ? Thank you!
$query = 'SELECT MAX(ID) as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$postid = $row['maxidpost']+1;
echo "p=$postid";
The improvement is debatable, but:
$query = 'SELECT MAX(ID) +1 as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "p = ". $row["maxidpost"];
You can do math in SQL statements, saving you from having to do the operation in PHP.
It'd be nice to know what you're using this for - if it's the next id to be inserted, using AUTO_INCREMENT would be safer. SELECT statements are generally given higher priority over INSERT/UPDATE/DELETE, and thus can read before an insert from another source -- which would risk duplicates.
Because you are returning one row, you should do something like:
$query = 'SELECT MAX(ID) as maxidpost FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$postid = $row['maxidpost']+1;
echo "p=$postid";
Otherwise seems about as good as you could do.
You can recalculate the post code after each post. Start with zero. Select it from the database, use that id, add one, save back to database.
Or you could use auto increment (if that is possible).

Categories