I am creating a report function were a manager can look up amendments to a user rota which is a mySQL table. This contains 5 columns Unique_ID ( Auto Increment), UserID(13 digit number), Date effected(Unix date), Date added(Unix date), Added_by(13 digit number).
To select the the correct data i was populating a drop down from another table which contains username and UserID ( a 13 digit number) however i am stuck with how to select the name ( as no one can remember all staff numbers) and it POST the corresponding user id to the next query.
<form action="<?=$_SERVER['php_SELF']?>" method="get">
<?
$loc = $usersite->UserLocation();
$username = "Uname";
$password = "Pword";
$hostname = "Hname";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("DBname",$dbhandle)
or die("Could not select database");
$query="SELECT name FROM `login1st` WHERE `Location` = '$loc'";
$result = mysql_query ($query);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result)){
echo'<option value="'.$nt['name'].'">'.$nt['name'].'</option>';
}
echo "</select>";
?>
<input type="submit" value="Search" class="buttons2">
</form>
this work fine and i have a drop down box with all staff names, is there a way to get the associated userid from the selection to a separate query? E.G
SELECT * FROM `$loc` WHERE `User_id` = (query result from drop down)
i am using the PHP_SELF as the result, I am hoping, will go into a table below the drop down. i am open to any other ways of doing this. Thanks in advance.
in the value-section you can define what to submit. So just change your query to get the UserId as well
$query="SELECT UserID, name FROM `login1st` WHERE `Location` = '$loc'";
and then just output the id in your selectbox:
echo'<option value="'.$nt['UserID'].'">'.$nt['name'].'</option>';
Related
I'm trying to recreate a make a booking form. They have a drop down select option with 3 values from the room table in the database. In the room table I have the values roomID, roomname, roomtype and beds. I need to have roomname, roomtype and beds displayed as one option in the drop down. So the 3 values will be on the same line if that makes sense. So for example it will say Brown, Double, 2beds and then I can select the options and will view another set of data. I currently know how to make a drop down with only one value in the line but how would I make a drop down menu that presents 3 values from a table?
Below is my code so far:
<?php
include "config.php";
$db = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
$query = $db->query("select roomname, roomtype, beds from room");
echo '<select room="roomname">';
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['roomname'].'">'.$row['roomname'].'</option>';
}
echo '</select>';
?>
I think this is what you are expecting.If you want to show roomname, roomtype, beds in one line just concatenate it.
<?php
include "config.php";
$db = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
$query = $db->query("select id,roomname, roomtype, beds from room");
echo '<select name="roomname">';
while ($row = $query->fetch_assoc()) {
echo '<option value="'.$row['id'].'">'.$row['roomname'].'-'.$row['roomtype'].'-'.$row['beds from room'].'</option>';
}
echo '</select>';
?>
I have set the task before me to use PHP in doing the following work on MySQL table:
Take the search input from HTML form and put it in the $POST['search']
Select table data
Number the table rows and put the number of rows into variable
Take the first value from the first row and check if it is equal to $POST['search']. If it is, print it together with the column name.
Take the n-th value from the first row and check if it is equal to $POST['search']. If it is, print it together with the column name.
Repeat that for each row of the table
I solved the HTML form, database connection, select table data and numbering the table rows (1,2 and 3)
I need help with 4 and 5.
Here is the code so far:
// 1 Izvuci podatke iz tabele
$db_host = '';
$db_user = '';
$db_pwd = '';
$database = '';
$table = '';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
// count the rows
$row_num= mysql_query("SELECT COUNT(*) FROM {$table}");
Can someone help me continue ?
Thank you.
I want to build a form to change the data in MySQL table. Firstly, I list all the data in the adminindex.php page. Then, I create a button to open the selected data in a form. I've done assigning the form fields to the main (pk) MySQL table. My problem started there when I need to fetch the foreign table data as the table contains many foreign data. As you guys know, a class may have many students, I have created the fields for class data, now the problem is in students data. Do I have to create many fields to fetch the data from MySQL foreign tables? If yes, could you guys guid me the code steps ? Thank you very much. Really appreciate your help :D
These are my steps:
Firstly I echo the rows, then I codes the form actions. Then, in adminpost.php, I create variables, link the fields and use UPDATE MYSQL to update the data in tables. I've succeeded in updating the primary table data but I'm stuck in foreign key data. Thanks :D
Have 2 pages. Display data in a form in first one and have update in the second. Here is a code for doing it one by one, you can build on it for multiple rows at a time if you want to.
edit.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = mysql_query("SELECT * FROM table1 where order by question_id limit 1") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$value1= $row['value1'];
$value2= $row['value2'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $value1;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $value2?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
update.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$id = mysql_real_escape_string($_POST["ID"]);
$value1 = mysql_real_escape_string($_POST["value1"]);
$value2 = mysql_real_escape_string($_POST["value2"]);
$query="UPDATE table1 SET value1 = '.$value1.', value2 = '.$value2.' WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Next
Might help to put your actual code up, but as i understand you are just wanting to edit the data that is already in your table? If thats the case :
//Connect to SQL DB
$dbcnx = #mysql_connect("localhost", "root", "password");
//Select DB
mysql_select_db("database_name", $dbcnx);
//Query DB
$sql = update table_name set column_name = "$variable" where column = "your_criteria";
#mysql_query($sql)
That will connect you to your SQL DB and update the records for you, hope thats what you needed
Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>£$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck
I'm new to PHP and I was wondering how to select a specific column from a row. For example if I wanted to display the first name of Joe Bugly where ID, first name, last name, and email are all columns.
Assuming that you don't want all columns that would be returned with select * from ... (a), you can simply list the desired columns explicitly:
select fname, lname from ...
For example, suppose you know your user ID is jbug01 and you just want the corresponding email address:
select email
from users
where userid = 'jbug01'
In terms of doing this within PHP, the following code snippet may help:
<?php
$conn = mysql_connect ("localhost", "paxdiablo", "supersekritsauce");
if (!$conn) {
die ('Could not connect: ' . mysql_error());
}
mysql_select_db ("my_database", $conn);
$result = mysql_query ("select email from users where userid = 'jbug01'");
while ($row = mysql_fetch_array ($result)) {
echo $row['email'] . "<br />";
}
mysql_close ($conn);
?>
(a) There are precious few cases where selecting * makes sense (other than tools that need to get all columns such as DB viewers).
You should usually prefer to be explicit with your column selections. This may allow you to detect problems with schema changes much earlier in the process than will be the case if you just blindly select everything.
It will also result in less information being transmitted which may not be important for small databases or systems where everything runs on the same box but it will affect scalability of your system, both in terms of data size and distribution across a network.
Try this:
$conn = mysql_connect("localhost","root");
mysql_select_db("DbName",$conn);
$query = "Select u.FirstName from Users u";
$results = mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['FirstName'];
}
Try this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
while ($id = $stmt->fetchColumn(0)) {
echo $id;
}
Mark answer if this helps.
Reference
This is actually an SQL question ;)
Depends on how you are selecting record of Joe Bugly. If you are selecting on basis of ID, then
SELECT fname
FROM your_table_name
WHERE ID = <ID of Joe Bugly>
This way you have selected a record and by applying fname in SELECT clause, you are filtering the number of columns you want