I am a complete beginner, so please bear with me. This is just a test project I am putting together to try to teach myself some of the basics.
I know that a lot of my commands are outdated and/or susceptible to injection, but I'd rather stick with this for now (many reasons).
I just had a question about trying to use SELECT from WHILE, and figured that out and got it to echo the correct response on the page.
Now, how do I make it echo that as a value for an HTML text box? It won't work, and I've tried to look for typos but I don't know what I am doing, frankly.
I see that the $studentid and $teacherinfo show fine, I presume because they are normal variables.
Can I somehow define two more variables for first name and last name further up in the page so that I do not need to include so much code in each input (and to keep it from being buggy)?
Here is my code for the page. The inputs will be hidden, but I have been making them text boxes for debugging purposes.
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
?>
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<h5>Student id: <?php echo $studentid ?></br>
Student first name: <?php
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
?>
</br>
Voted for: <?php echo $teacherinfo ?>
</h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['first_name'];
} ?>"/>
</br>
<input type="text" name="last_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['last_name'];
} ?>"/>
</br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
You can't use while because your query return only one student. You have to use if instead of while. If your query return many students you can use while.
Try this code:
<?php
if($row = mysql_fetch_array($result)){
?>
Student first name: <?php echo $row['first_name'];?>
</br>
Voted for: <?php echo $teacherinfo ?></h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php echo $row['first_name'];?>"/></br>
<input type="text" name="last_name" value="<?php echo $row['last_name'];?>"/></br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
<?php
}
?>
I hope this help.
I tried to build a code that will help you. Remember that you use last_name, but does not return the field in SQL.
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name`,`last_name`,`student_id` FROM `students` WHERE student_id = $studentid",$connection);
while($row = mysql_fetch_array($result)){
echo "<h5>Student id: $row['student_id'] </br>" .
"Student first name: $row['first_name'] </br>" .
"Voted for: $teacherinfo </h5> " .
"<input type='text' name='student_id' value='$row[\'student_id\']' /></br>" .
"<input type='text' name='first_name' value='$row[\'first_name\']' /></br>" .
"<input type='text' name='last_name' value='$row[\'last_name\']' /></br>" .
"<input type='text' name='teacher' value='$teacherinfo' /></br>"
}
?>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
WHILE I left because I do not know if your query can return more than one record, despite appearing to be a key. If you do not need to check the response of the Ragnar.
Related
So im still relatively new to php and im trying to create a form that autofill's with information from a table. The table is called students and has the students id, first and last name, and their address. Im trying to make it so it only autofill's with the information of the student with a certain id, for example if the students id is 102 it fills the textboxes with their info.
I have some code which i thought would work but its telling me somethings wrong with the while loop and i don't know what.
Edit: The error i keep getting is this:"mysqli_fetch_assoc() expects parameter 1 to be mysqli_result".
PHP code:
<?php
require_once ('Connection.php');
$query = "SELECT * from students where Id = 102";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
?>
Html Form:
<form action="http://localhost/test.php" method="post">
<p>Student ID:
<input name="stu_id" size="5" value="<?php echo $row['student_id']; ?>" pattern="^\d{3}" required autofocus /><?php echo $row['student_id']; ?>
</p>
<p>First Name:
<input type="text" name="fname" size="30" value="<?php echo $row['stu_Fname']; ?>"/>
</p>
<p>Last Name:
<input type="text" name="lname" size="30" value="<?php echo $row['stu_Lname']; ?>"/>
</p>
<p>Address:
<input type="text" name="address" size="30" value="<?php echo $row['stu_addr']; ?>"/>
</p>
<p>
<input type="submit" name="submit" value="Send"/>
</p>
</form>
EDIT: Connection code:
<?php
DEFINE ('DB_User', 'testuser');
DEFINE ('DB_Password', 'abc123*');
DEFINE ('DB_Host', 'localhost');
DEFINE ('DB_Name', 'student');
//start database connection
$dbc = new mysqli(DB_Host, DB_User,DB_Password,DB_Name);
if(mysqli_connect_errno())
{
printf("can't connect to database.", mysqli_connect_error());
exit();
}
?>
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
You're not actually accomplishing anything within the while loop above. There is no assignment, nor output.
Each iteration of the while loop will grab a row (if there is one in the database). Assuming that the row has the four columns you've listed, you can print the data to the screen. For example:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['student_id'] . ", ";
echo $row['stu_Fname'] . ", ";
echo $row['stu_Lname'] . ", ";
echo $row['stu_addr'];
}
Assuming you're outputting a form for each student, you can place the form logic within the while loop.
Not sure what I am doing wrong here. I would like to create a search that allows the user to do an and or search.
However when I use the below code, if I type in Brown as Colour1 it will return all results, same as post code.
The goal is to allow the user to search multiple fields to return a match. So Colour1 and Postcode
<html>
<head>
<title> Logo Search</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width: 250px;
text-align: left;
}
</style>
</head>
<body>
<h1> National Logo Search</h1>
<form method="post" action="singlesearch2.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%')
or
('Colour2' like '%$criteria2%')
or
('PostCode' = '%$criteria3%')
or
('Suburb' like '%$criteria4%')
LIMIT 0,5";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>
I can get it to work correctly when I use a dropdown list to select the criteria however I would like them to have multiple options to filter results.
<form method="post" action="multisearch.php">
<input type="hidden" name="submitted" value="true"/>
<label>Search Category:
<select name="category">
<option value="Colour1">Main Colour</option>
<option value="Colour2">Secondary Colour</option>
<option value="PostCode">Post Code</option>
</select>
<label>Search Criteria: <input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
echo "connected " ;
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE $category LIKE '%$criteria%'";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
In general you run your query with AND condition because it has criteria and you have it means that you have to show value by matching each criteria with receptive column. but it also depends on users or client how they want to show their field.
In short it doesn't have any rule how to show.
Played around with it for a bit and found the answer. I needed to define the criteria. see below code
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')
As the title suggests I am trying to link a populated drop down list to a form on another page.
My dropdown list is currently connected to my database which displays the addressID's of 6 people. So when the user selects for example AddressID 3 it will take them to the next page (customerdetails.php) which will then allow them to update the form which will update the database accordingly.
My current code is as follows
<?php
//adding the database connection
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the databse
$dbhandle = mysql_connect ($hostname, $username, $password)
or die ("Unable to Connect to MySQL");
echo "Connected to MySQL";
//selecting the database we want to work with
$selected = mysql_select_db("my_guitar_shop2", $dbhandle)
or die("Could not select my_guitar_shop2");
?>
<p>AddressID:</p> <br>
<?php
$sql = "SELECT addressID FROM addresses";
$result = mysql_query($sql);
echo "<select name='addressID' onchange = 'getAddressID(this)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['addressID'] ."'>" . $row['addressID'] ."</option>";
}
echo "</select>";
?>
Now on the customerdetails.php page i have the code:
<?php
$adrresIDSelected = $_GET['addressID'];
?>
For the life of me I cannot seem to connect the 2 pages together.
Am i anywhere near the correct path? I would prefer not to use javascript as I have no prior knowledge of it.
Many thanks in advance
UPDATE
customerdetails.php page
<?php
//adding the database connection
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the databse
$dbhandle = mysql_connect ($hostname, $username, $password)
or die ("Unable to Connect to MySQL");
echo "Connected to MySQL";
//selecting the database we want to work with
$selected = mysql_select_db("my_guitar_shop2", $dbhandle)
or die("Could not select my_guitar_shop2");
?>
<?php
$addrresIDSelected = $_GET['addressID'];
?>
Contact Form
<form class="form">
<p class="first">
<label for="name">FirstLine</label>
<input type="text" name="firstline" id="first" />
</p>
<p class="second">
<label for="email">SecondLine</label>
<input type="text" name="secondline" id="second" />
</p>
<p class="city">
<label for="web">City</label>
<input type="text" name="city" id="web" />
</p>
<p class="state">
<label for="web">State</label>
<input type="text" name="state" id="web" />
</p>
<p class="zip">
<label for="web">Zip Code</label>
<input type="number" name="zip" id="web" />
</p>
<p class="update">
<input type="button" value="Update" />
</p>
<p class="remove">
<input type="button" value="Remove" />
</p>
</form>
First solution (no Javascript)
For a solution without Javascript, you will need to use the select within a form element and use a submit button too to send the information completed/selected in the form to the desired page:
...
<form action="customerdetails.php" method="get">
<select name="addressID">
<?php
$sql = "SELECT addressID FROM addresses";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['addressID'] ."'>" . $row['addressID'] ."</option>";
}
?>
</select>
<input type="submit" value="Take me to the other page">
</form>
...
UPDATE - Second solution (with Javascript)
For using the getAddressID Javascript function to send the ID instead of using a form, you will need to update the function a bit:
<script>
function getAddressID (option) {
var addressID = option.value;
// you do not need the <your_domain> prefix here, as probably both your php scripts are on the same server/domain and same folder
window.location.replace ("customerdetails.php?addressID =" + addressID);
//-----------------------------------------------------^
// Extra space must be removed!
}
</script>
this script displays data from a specific email address which the user enters.
the snippet of code below displays the data in a textfield at the top of the page however I want to display the data in a textfield in the body of text.
echo '<input name="login" type="text" value="' . $result['name'] . '>';
What do I change in the above code to enable me to do this.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="orders"; // Table name
$email = $_POST['textfield'];
$db = new PDO('mysql:host='.$host.
';dbname='.$db_name.
';charset=UTF-8',
$username, $password);
$stmt = $db->prepare('SELECT * FROM `orders` WHERE `email`=:email LIMIT 1');
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
?>
form:
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $result['name']?>"> //I want to display results here
</form>
if both the code exists in the same file.. this will work
<input type="text" name="name" value="<?php echo $result['name']?>">
and if you want to check if there are rows returned you can use
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
edited the code so that you know what exactly you want to do
First: Replace this code
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
just keep $result = $stmt->fetch(PDO::FETCH_ASSOC); and
if($stmt->rowCount()<=0) echo "Email not found in the database!";
Second: now in HTML section
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
As long as you don't clobber $result you can do:
<input type="text" name="name" value="<?php echo $result['name']; ?>"> //I want to display results here
echo '<input name="login" type="text" value="' . $result['name'] . '">';
Just add a double quote to the echo'd string.
It's pretty easy to accomplish. Of course make sure that the $results array is included in the session for the desired HTML page that you are working on.
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $results['name']?>"> //I want to display results here
</form>
I have looked everywhere here in Stackoverflow and I´ve searced 16.493 sites on Google but no answers to the most basic thing in php (edit record)
I´ve managed to code the most complicated stuff - but this is like a cancer and would also help others.
I have to files - edit.php - and update.php
edit.php works and it retrieves the data from the record
Here is the edit.php
<?php
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM cloudbig WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
?>
<form name="form1" method="post" action="update.php">
<input type="text" name="fs" value="<?php echo $texti ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
<?php
}
?>
and here is update.php
<?php
$id = $_REQUEST["id"];
$fs = $_POST["fs"];
$texti = $_POST["texti"];
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("db") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE cloudbig SET fs = '$fs', texti = '$texti' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
I´ve done a whole news/online magazine site in php but simple edit.php function is a problem
I think that the short answer is that you never post the "id" up to the update.php script. Your form needs to look like this:
<form name="form1" method="post" action="update.php">
<input type="hidden" name="id" value="<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will send the id into the POST array where it can be accessed by $id = $_REQUEST["id"];
You can also accomplish this by sending it via _GET by modifying the form action:
<form name="form1" method="post" action="update.php?id=<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will put it in the $_GET array where it will also be seen in the $_REQUEST array.
Lastly, there are some MAJOR ISSUES with your code:
First and foremost, it is subject to SQL injection! You MUST escape
your variables before passing them into a MySQL query.
Second. As pointed out by iDifferent, you appear to bve echoing the wrong value into the fs field (you're setting it equal to the texti field)
Third, why do you have this loop?
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
If you're fetching by ID you should never have duplicates. Make sure that ID is a primary key and there is no reason to check for multiple rows.