Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>
Related
How to set a single record to a user profile? For example username, password, email, and wallet. I need to show only date for each user login. This script shows wallet but first user id person and I need to show the user who is logged in.
HTML and PHP:
<?php
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT wallet FROM users LIMIT 1");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
while($record = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
To answer you fully.
Start by updating your user table when your users log in by changing the status true or false depending on your implementation.
Also start a session
your code now becomes
<?php
session_start();
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Login logics
$res= mysqli_query($con,"SELECT * FROM users where username='user' and password ='pass'");
if($res)
{
$user = mysql_fetch_row($res);
//Keep track of the current logged in user
$_SESSION['user'] = $user['id'];
}
//Now your logic to get wallet or any other thing for the current logged in user
$currentUser = $_SESSION['user'];
$result = mysqli_query($con,"SELECT wallet FROM users where id=".$currentUser.");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
$record = mysqli_fetch_row($result)
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
echo "</table>";
mysqli_close($con);
?>
Hope this helps..
Work with the Edit you dont need the While loop since you are looking for just a record
If there's duplicated topic - please, forgive me, but i haven't found a solution yet. First of all, I've got one php file (update.php). This file contains:
<form action='update.php' method='post'>
<table border='1'>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "exchange";
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($conn,"utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
echo "</tr>";
}
}
$conn->close();
?>
<table>
There's 14 rows and 5 columns in my db. How do i update every row in columns 'buy' and 'sell' on 'click' (isset submit button) with new values? I've tried with ID[], buy[], but I've got problems with loop and i cannot handle it. I'm running MySQL on localhost, also i know that only last row will be updated without running loop, but still...
I am assuming you have corresponding php code to process the input, here is a sample of what you'll need to do for the HTML when creating the form:
if ($result->num_rows > 0) {
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
echo "<td>".$row["name"]."</td>";
echo "</tr>";
}
}
On the php side to process the input, you can do something like this:
$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
//do insert with $id
}
This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
Closed 1 year ago.
I am new to php coding.
I am adding each row delete button, but it should not working.
This is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM venu ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
<th>rollnumber</th>
<th>address</th>
<th>phonenumber</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><form action='delete.php' method='POST'><input type='hidden' value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
This is my delete code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$name = $_POST['name'];
$id = $_POST['id'];
$rollnumber = $_POST['rollnumber'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
if($name!='' and $id!='')
{
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>
I am trying to delete each row using a button, but it is not working.
In your html view page some change echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>"; like bellow:
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>";
echo "</tr>";
}
?>
PHP delete code :
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM venu WHERE id = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
} else {
echo "ERROR";
}
}
?>
Note : Please avoid mysql_* because mysql_* has beed removed from
PHP 7. Please use mysqli or PDO.
More details about of PDO connection http://php.net/manual/en/pdo.connections.php
And more details about of mysqli http://php.net/manual/en/mysqli.query.php
First you need to change your button like
echo "<td>Delete</td>";
this will send the ID of the row which you want to delete to the delete.php
Secondly you need to change a bit your delete.php currently is wide open for SQL injections. Try using MySQLi or PDO instead
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM venu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
}
Of course if you need to add more parameters in delete query you should pass them also with the button..
EDIT: Simple example for update record
You can put second button on the table like
echo "<td>Update</td>";
Then when you click on it you will have the ID of the record which you want to update. Then in update.php
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param('sisi', $name, $rollnumber, $address, $id);
$stmt->execute();
$stmt->close();
}
Here ( in update.php ) you can have form which you can fill with new data and pass to variables $name, $rollnumber, $address then post it to update part.
Something to start with: PHP MySqli Basic usage (select, insert & update)
change up your query to use the dynamic value entered by the user, right now it is hard coded in there.
session_start();
require_once 'conn.php';
class myClass extends dbconn {
public function myClassFunction(){
try {
$id = $_GET['id'];
if(isset($_GET['id'])) {
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $this->connect()->query($sql);
$stmt->bind_param('i', $id);
header("location: ../filepath/index.php");
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
}
This line is wrong, you need to set the WHERE clause to the data you get from the hidden input value
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
Should be:
$sql = mysql_query("DELETE FROM 'venu' WHERE address='"._POST['address']."'");
And in the little form you are using, change:
<input type='hidden' value='".$row["address"]."'/>
to:
<input type='hidden' name='address' value='".$row["address"]."'/>
I have a table with an "id" that automatically increment each time a new entry is added to the table. In the same table, I also store images.
Regardless of the id incrementing the image is always the same.
I would like the images to change based on the "id". How do I achieve this?
Find below my code to file: displayImage.php:
$link = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("flightSched") or die(mysql_error());
// get the image from the db
$sql = "SELECT image FROM flightSched";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result,1);
// close the db link
mysql_close($link);
And the code with the incrementing "id"
$result = mysql_query("SELECT id, flightNo, airline, origin, arrivalTime, status
FROM flightSched ")
or die(mysql_error());
$variable= 'id=basicBoard';
//echo $variable;
echo "<table border='1' id='customers'>";
echo "<tr> <th></th> <th>Flight No</th> <th>Airline</th> <th>Origin</th> <th>Arrival</th> <th>Status</th> ";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr " . $variable . "><td>";
echo '<img src="displayImage.php?id=' . $row['id'] . ' " width="40" height="40" >';
echo "</td><td>";
echo $row['flightNo'];
echo "</td><td>";
echo $row['airline'];
echo "</td><td>";
echo $row['origin'] . $row['id'];
echo "</td><td>";
echo $row['arrivalTime'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
if ($variable == 'id=basicBoard')
{
$variable = 'class=alt';
//echo $variable;
}
elseif ($variable == 'class=alt')
{
$variable = 'id=basicBoard';
//echo $variable;
}
}
echo "</table> <br/> <br/>";
Looking forward to your reply.
Any help is greatly appreciated!
You haven't used the ID to limit the results in your displayImage.php file.
Change
$sql = "SELECT image FROM flightSched";
to
$sql = "SELECT image FROM flightSched WHERE id = '$_GET[id]'";
This will get it working but is an example, but please sanitize the GET value instead of just using it directly in the sql.
I've got a query that displays a table with information about a message, I also have a column that gives the option to select the messages that the user wants to delete with a checkbox, once they have ticked the messages they want to delete, they then click on a submit button which takes them to the process page where the SQL statement to delete each selected message is made; however, the statement doesn't seem to work, this is what I have so far:
THE MESSAGE DISPLAY PAGE:
if ($_SESSION['user_session'] == "$current_user")
{
{
echo "<table border='1'>
<tr>
<th>Message ID</th>
<th>Username</th>
<th>Subject</th>
<th>Message</th>
<th>Delete?</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['message_id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['sub'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "<td><input type='checkbox' name='check_list[]' value='" . $row['message_id'] . "' /></td>";
echo "</tr>";
}
echo "</table>";
}
}
THE PROCESS PAGE WITH SQL STATEMENT:
if(!empty($_POST['check_list']))
{
foreach($_POST['check_list'] as $check)
{
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX")
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle)
or die("Could not select examples");
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
}
if ($result)
{
echo 'Messages Deleted';
}
}
if(!empty($_POST['check_list']))
{
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
$result = mysql_query("DELETE FROM message WHERE message_id IN (" . implode(',', $_POST['check_list']) . ")", $dbhandle);
if ($result !== false)
echo 'Messages deleted.';
}
You obviously should implement some more testing of the contents of $_POST['check_list'] before executing the query. We don't want evil people to do silly stuff.
As far as I can see there's nothing wrong with your code, you should really try a var_dump($check) before the SQL query to output what it contains, and a var_dump($_POST['check_list']) at the very beggining of the second page.
Also, I suggest you to take out the database connection of the foreach as you are doing multiple innecesary connections, like this:
if(!empty($_POST['check_list'])) {
// Output the variable $_POST['check_list']
var_dump($_POST['check_list']);
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
foreach($_POST['check_list'] as $check) {
// Output the $check variable to see what it contains
var_dump($check);
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
// For each $check, verify what message_id got deleted
if ($result) {
echo 'Message ID Deleted: ' . $check;
}
}
}