lastInsertId get from different function - php

I have a form, wich sends information to the database (When filled in)
Form function:
function train_add() {
$sql = "INSERT INTO train_information "
. "(train_id, image, train_name, tare_weight, number_of_bogies, number_of_axles, wheel_diameter_min, wheel_diameter_max)"
. "VALUES (train_id, :image, :train_name, :tare_weight, :number_of_bogies, :number_of_axles, :wheel_diameter_min, :wheel_diameter_max) ";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':image', $_POST['image'], PDO::PARAM_STR);
$sth->bindParam(':train_name', $_POST['train_name'], PDO::PARAM_STR);
$sth->bindParam(':tare_weight', $_POST['tare_weight'], PDO::PARAM_STR);
$sth->bindParam(':number_of_bogies', $_POST['number_of_bogies'], PDO::PARAM_STR);
$sth->bindParam(':number_of_axles', $_POST['number_of_axles'], PDO::PARAM_STR);
$sth->bindParam(':wheel_diameter_min', $_POST['wheel_diameter_min'], PDO::PARAM_STR);
$sth->bindParam(':wheel_diameter_max', $_POST['wheel_diameter_max'], PDO::PARAM_STR);
$sth->execute();
return $this->pdo->lastInsertId('train_id');
}
Right. So when the form is filled in, it is send to the database (works).
The user will be redirected in 10 seconds (Did this for myself to see if any errors come up).
<?php
//Train information is send to the database, and selects the ID of the just added train//
$add_train = $database->train_add();
?>
<meta http-equiv="Refresh" content="10;url=http://localhost:8080/show_axle_table.php?train_id="<?php ['$id'] ?> >
show_axle_table.php:
<?php
$show_axle = $database->axles();
?>
<div id="train_select_table">
<table>
<tr>
<th>Train id</th>
<th>Number of bogies</th>
<th>Number of axles</th>
</tr>
<div id="loopRow">
<?php
foreach($show_axle as $res){
//Loop trough results, generate a tablerow every time
?>
<tr>
<?php
echo "<td>" . $res['train_id'] . "</td>";
echo "<td>" . $res['number_of_bogies'] . "</td>";
echo "<td>" . $res['number_of_axles'] . "</td>";
?>
</tr>
<?php
}
?>
</div>
</table>
</div>
And the function:
function axles(){
$id2 = $this->train_add($id);
$sql = "SELECT * FROM train_information WHERE train_id = '$id2'";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $_GET["train_id"], PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
Now the table shows me a ID of a train. But it adds 1 so everything else is empty.
For example:
User fills in form. Sends it to Database (train_add) It gets and id of 1 and is done.
Then the page redirects to the show_axle_table.php. Function should get the last inserted id. but it shows me a ID of 2.
Also i want the ID to be shown in the top of my page like:
show_axle_table.php?train_id="<?php ['$id'] ?>
But right now it shows nothing. (train_id=)

Update like this:
<?php
//Train information is send to the database, and selects the ID of the just added train//
if (!(isset($_GET['train_id]) && $_GET['train_id'])) {
$add_train = $database->train_add();
}
?>
<meta http-equiv="Refresh" content="10;url=http://localhost:8080/show_axle_table.php?train_id="<?php echo $add_train; ?> >
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="train_select_table">
<table>
<tr>
<th>Train id</th>
<th>Number of bogies</th>
<th>Number of axles</th>
</tr>
<div id="loopRow">
<?php
foreach($show_axle as $res){
//Loop trough results, generate a tablerow every time
?>
<tr>
<?php
echo "<td>" . $res['train_id'] . "</td>";
echo "<td>" . $res['number_of_bogies'] . "</td>";
echo "<td>" . $res['number_of_axles'] . "</td>";
?>
</tr>
<?php
}
?>
</div>
</table>
</div>
And function as
function axles($id){
$sql = "SELECT * FROM train_information WHERE train_id = '$id'";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $_GET["train_id"], PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}

Related

Get a button to delete a record and link to another page

I am displaying an HTML table of appointment bookings, and in each row there is a button that lets the user delete each individual booking. Currently it instantly deletes the record, but I was wondering if it was possible to display some sort of confirmation message before deleting, and if it was also possible to redirect the user to a new page at the same time.
<?php
require('header.php');
require('config/db_connect.php');
adminCheck();
$adminEmail = $_SESSION['email'];
// make sql
$sql = "SELECT * FROM bookings WHERE email='$adminEmail'";
// get query result
$result = mysqli_query($connection, $sql);
// fetch result in assoc array (one row, single student)
$bookings = mysqli_fetch_assoc($result);
if (isset($_GET['deleteId'])) {
// Sanitize input for SQL injection risk
$deleteId = mysqli_real_escape_string($connection, $_GET['deleteId']);
if(!is_null($deleteId)) {
$sqlB = "DELETE FROM bookings WHERE id = '$deleteId'";
mysqli_query($connection, $sqlB);
// Could use a modal otherwise this instantly deletes the record
}
}
?>
<!DOCTYPE html>
<html>
<head>
<h2> All bookings </h2>
</head>
<body>
<table class='striped white'>
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Surname</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
// This doesn't echo the first record in the database for some reason
echo
"<tr>".
"<td>". $row['id'] . "</td>" .
"<td>". $row['firstName'] . "</td>" .
"<td>". $row['surName'] . "</td>" .
"<td>". $row['date'] . "</td>" .
"<td>". $row['timeSlot'] . "</td>" .
"<td>Delete Row</td>" . // trying to link to a new page too
"</tr>";
}
} else{
echo 'no bookings';
}
?>
</tbody>
</table>
</body>
</html>
<?php require('footer.php'); ?>
Furthermore, when the table is displayed, the first record is always missing for some reason too. Is there something I'm missing? Thank you.
For the first problem, you can do something like this, using javascript to ask for confirmation
Delete Row</td>'; }">Delete row </a>
For the second thing, maybe try to add an html redirect only if there is the get variable set
<?php if(isset($_GET['deleteId'])) { ?>
<meta http-equiv="refresh" content="0; url=http://example.com/" />
<?php } ?>

How to list out two different product's details at the same table with php

I only can list out all the data row by row but I want to list out those 2 products like this from top to bottom, not row by row within
index.php
while ($row = mysqli_fetch_array($results)) {
echo '<td><'.$row['name'].'></td>';
}
server.php
$db = mysqli_connect('localhost','root','','crud');
$results = mysqli_query($db, "SELECT * FROM info");
If I really understand, you want each product to be in a different line. If yes, you could create new rows directly inside your loop like this
while ($row = mysqli_fetch_array($results)) {
echo '<tr><td>'.$row['name'].'</td></tr>';
}
<?php
while($row = mysqli_fetch_array($results)){
$detail_row.="<td>" . $row['items'] . "</td>";
$category_row.="<td>" . $row['items'] . "</td>";
}
?>
<table>
<tr>
<td>Details</td>
<?php echo $detail_row; ?>
</tr>
<tr>
<td>Categories</td>
<?php echo $category_row; ?>
</tr>
</table>

How can I use a select box in HTML to search for a specific user in the database and show that information on a table?

I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>

crud delete not working anymore

i used the crud delete method and it works for me, but when i tried it with a different database and table it keeps saying "Invalid argument supplied for foreach()"
this is my "vacature-verwijderen.php" where you should be able to delete it
<div>
<table id="tabel">
<thead>
<tr>
<th>Functie</th>
<th>Omschrijving</th>
<th>Salaris</th>
</tr>
</thead>
<tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM vacature ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['functie'] . '</td>';
echo '<td>'. $row['omschrijving'] . '</td>';
echo '<td>'. $row['salaris'] . '</td>';
echo '<td width=250>';
echo '<a class="button " href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="button" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
and then when you click delete you go to "delete.php" which looks like this
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( !empty($_POST)) {
$id = $_POST['id'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM vacature WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: vacature-verwijderen.php");
}
?>
i don't know what is wrong since it used to work, also my database table looks like this
foreach ($pdo->query($sql) as $row) {
That's what is wrong. $pdo->query($sql) already returns your $row.
Use a while instead so that it do the query and returns you the new row as long as there is data to fetch :
while ($row = $pdo->query($sql)) {
Also :
$sql = "DELETE FROM vacature WHERE id = ?";
The table you provided doesn't contain any field named id, although there is one named vacature_id. You might want to change that too :
$sql = "DELETE FROM vacature WHERE vacature_id = ?";
Don't hesitate to come back if it doesn't solve your issue.

Home displaying all users info

I built a simple CRUD using PHP but the home file is displaying all the info I have in the database, even the info added by other users. How can I filter this to show only the logged users info?
Here is the home.php file:
<?php
session_start();
if(isset($_SESSION['user'])){
echo "Logado como ". $_SESSION['user'];
}
else {
echo"<script language='javascript' type='text/javascript'>alert('Voce deve estar logado');window.location.href='index.php';</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Perfil</title>
</head>
<body>
</br>
Sair</br>
<h2 align="center">Lista de contatos</h2>
<table align="center" border="1">
<tr>
<th>Nome</th>
<th>Telefone</th>
<th>Endereco</th>
<th>Editar</th>
<th>Deletar</th>
</tr>
<?php
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("forms") or die("Cannot connect to database"); //connect to database
$query = mysql_query("Select * from contatos"); // SQL Query
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['nome'] . "</td>";
Print '<td align="center">'. $row['telefone'] . "</td>";
Print '<td align="center">'. $row['endereco'] . "</td>";
Print '<td align="center">Editar </td>';
Print '<td align="center">Deletar </td>';
Print "</tr>";
}
?>
</table>
<div align="center">
Adicionar contato</br>
</div>
</body>
</html>
Wherever you are assigning $_SESSION['user'] also assign the user record id to the session.. this way you can add a where clause to your sql and fetch only the desired record..
Quick example:
if(isset($_SESSION['user_id'])) {
$sql = "SELECT * FROM contatos WHERE id = {$_SESSION['user_id']}";
// ....
}
Use id or name to differentiate records
$sql = "SELECT * FROM contatos WHERE nome = ".$_SESSION['user'];
$sql = "SELECT * FROM contatos WHERE id = ".$_SESSION['id'];
You must have an autoincremented primary key which wil be your id.

Categories