primary key and foreign key in php - php

Hi guys i really need some help down here with these primary keys and foreign keys.I've tried searching for leads but i'm not able to figure it out. Please help me out here and i'm sorry if this question has been asked before
i've got 2 tables and their columns
client
id(pk) | organisation | description | token
Transaction
trx_id | c_id(fk) | trx_description | trx_date | action | no_of_token
In the transaction table, all the values in it were manually key in by me through php myadmin even selecting the c_id which is the foreign key.so my question is for example i create a new organisation called ccc, i want it to get automatically assigned to the c_id of 3 in the transaction table.Also everytime i update the tokens, it should display in the trasaction table as trx_id(i already set it as auto increament)
but the c_id should match the organisation i've selected and increment the row accordingly.........Hope you guys can help me out quick and i'm sorry if i'm confusing you......I can post the code if you guys want :)
This script below add the client
<?php
include 'connection.php';
// Get values from form
$organisation=$_POST['organisation'];
$description=$_POST['description'];
$token=$_POST['token'];
// Insert data into mysql
$sql="INSERT INTO client(organisation, description, token)VALUES('$organisation', '$description', '$token')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='login_success.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
transaction table script
<?php
include 'connection.php';
?>
<html>
<head>
<title>ThaiCreate.Com PHP & MySQL Tutorial</title>
</head>
<body>
<form action="add.php?id=<?=$_GET["id"];?>" name="frmEdit" method="POST">
<?
$strSQL = "SELECT * FROM client WHERE id = '".$_GET["id"]."' ";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if(!$objResult)
{
echo "Not found id=".$_GET["id"];
}
else
{
?>
<table width="600" border="1">
<tr>
<th width="91"> <div align="center">id </div></th>
<th width="160"> <div align="center">organisation </div></th>
<th width="198"> <div align="center">current token </div></th>
</tr>
<tr>
<td><?=$objResult["id"];?></div></td>
<td><?=$objResult["organisation"];?></td>
<td><?=$objResult["token"];?></td>
</tr>
</table>
How many tokens do you want to add to this organisation: <input type="text" id="newToken" name="newToken" /><br/>
Please fill up the reason for adding the tokens : <input type="text" id="reason" name="reason" /><br/>
<input type="submit" name="submit" value="submit">
<?
$newToken = isset($_POST['newToken']) ? $_POST["newToken"] : "";
$reason = isset($_POST['reason']) ? $_POST["reason"] : "";
$sql="UPDATE client SET token = token + '$newToken' WHERE id = '".$_GET["id"]."' ";
$result=mysql_query($sql) or die ("Error Query [".$sql."]");
?>
<?
if ($newToken == true)
{
mysql_query("START TRANSACTION");
$date = date("Y-m-d H:i:s");
$query_string_count = "SELECT count(*) AS num FROM transaction WHERE c_id =" . $_GET["id"];
$query = mysql_query($query_string_count);
$result = mysql_fetch_array($objQuery);
$num = $objResult["num"];
INSERT INTO `transaction` (`trx_id`, `c_id`, `trx_description`, `trx_date`, `action`, `no_of_token`) VALUES ($num + 1, $_GET["id"], '$reason', '".$date."', 'Add token', '$newToken')";
mysql_query("COMMIT TRANSACTION");
?>
<?
header("Location:login_success.php");
}
else {
}
?>
<?
}
mysql_close();
?>
</form>
</body>
</html>

The problem is that you set up the trx_id as auotoincrement.
If you need keep separated the number of transcation of each client then the trx_id shouldn't be autoincrement.
For example each time you do insert on the transaction table:
1: start new transcation
2: number = count the number transactions that has as c_id the id of the client of interest
3: insert into transaction and set trx_id = number + 1
4: commit transaction
Note: in this case trx_id could not unique as you have more clients. If you need it you can insert a new column in the transaction table that is primary_key and in this case autoincrement
Here a snapshot of code to do what i described:
//new db transaction
mysql_query("START TRANSACTION");
// count number of transaction for clients $_GET["id"]
$query_string_count = "SELECT count(*) AS num FROM transactions WHERE c_id =" . $_GET["id"];
$query = mysql_query($query_string_count);
$result = mysql_fetch_array($objQuery);
$num = $objResult["num"];
//insert new transaction for client $_GET["id"] with id $num + 1
INSERT INTO `transaction` (`trx_id`, `c_id`, `trx_description`, `trx_date`, `action`, `no_of_token`) VALUES ($num + 1, $_GET["id"], '$reason', '".$date."', 'Add token', '$newToken')";
//COMMIT -> persist on db
mysql_query("COMMIT TRANSACTION");

Related

Increment ID by getting the last record id from mysqli table

I am trying to get the last Employee ID from my Sqli table, increment the id retrieved from the table and insert the new value into the table along with the new record.
The code is not working as the table is not getting updated.
<form method="POST">
<input type="text" name="brn" placeholder="Branch"/>
<input type="text" name="nam" placeholder="Enter Name"/>
<input type="submit" name="insert">
<?php
$db=mysqli_connect("localhost","root","","test");
session_start();
if(isset($_POST['insert']))
{
$brn = $_POST['brn'];
$nam = $_POST['nam'];
$qry = "SELECT * FROM emp";
$result=mysqli_query($db,$qry);
$row = mysqli_fetch_array($result);
$empid= $row["empid"];
$empid++;
$query = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
mysqli_query($db,$query);
mysqli_close($db);
}
?>
</form>
You need some changes in your code.
You are selecting the first "EmpId" instead of the last one and if you are having the column empid as primary key, it will show the error of primary key violation.
Therefore change your query to somewhat this:
$qry = "SELECT * FROM emp order by empid desc limit 1";
It will return one row.
And, if you just need the last empid then i would suggest you to go with only:
$qry = "SELECT empid FROM emp order by empid limit 1";
This is more resource effective query.
****Happy Coding.****
you can try this. I hope it will help you.
$sql = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
if(mysqli_query($db, $sql)){
$last_id = mysqli_insert_id($db);
echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Inserting value in table with the click of a button

I'm working on a file called test.php.
What I'm trying to do is, to insert a value into a table by clicking a submit button
I have two tables, tbl_1 and tbl_2
tbl_1
id | name | age
4 | john | 20
9 | tim | 25
8 | lea | 22
While tbl_2 have the same structure as tbl_1, it is empty or without any value in it... the idea is that I want to have a button, after clicking on that button, it will insert the value of tbl_1 into tbl_2 based on the id
The question is, how do I fill in tbl_2 with the value of tbl_1, through a click of a submit button?
I made a form, trying to bring the value from tbl_1 to tbl_2, but to no avail...
<form action="test.php?id" method="post">
<input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>
<?php
if(isset($_POST['submit']))
{
$io = $_POST['io'];
$no_kes = $_POST['no_kes'];
$SQL = "INSERT INTO tbl_2(name, age) VALUES ( '".$name."', '".$age."')";
$result = mysql_query($SQL);
}
?>
Below is how my table looks like on the web.
Below is the code for the table I constructed.
<table class="table table-striped table-bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
<?php
// Read
$per_page = 7;
if (isset($_GET["page"]))
$page = $_GET["page"];
else
$page = 1;
$start_from = ($page-1) * $per_page;
$sql = "select * from tbl_1";
$result = $mydb->query($sql);
while ($readrow = $result->fetch_array()) {
?>
<tr>
<td><?php echo $readrow['id']; ?></td>
<td><?php echo $readrow['name']; ?></td>
<td><?php echo $readrow['age']; ?></td>
<td>
There are couple of things you need to change in your code, such as:
You need to change your form's action attribute in the following way,
<form action="test.php?id=<?php echo $readrow['id']; ?>" method="post">
<input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>
Subsequently, you have to catch a particular row's id in test.php page the following way,
$id = (int)$_GET['id'];
Finally perform your INSERT operation in the following way,
if(isset($_POST['submit'])){
$id = (int)$_GET['id'];
$SQL = "INSERT INTO tbl_2(name, age) SELECT name, age FROM tbl_1 WHERE id = {$id}";
$result = mysql_query($SQL);
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Since you already mentioned tbl_2 has the same structure as tbl_1, you may simply construct your DB query as:
insert into tbl_2(id, name, age) select tbl_1.id, tbl_1.name, tbl_1.age from tbl_1 left join tbl_2 on tbl_1.id = tbl_2.id;
What this does:
It scans tbl_1 and inserts any values that are missing in
tbl_2 table. It has the potential to insert duplicate values. For
that, you should have enough robust DB structure that avoids
duplicate values in a table (using unique keys etc).

Insert selected radio values into a specific id of the table- php mysql

I have a table in database, and when want to reject or accept someone's application i just select the radio button and send the value to the table in database.
But the problem is that the value is assigned to new row and not to the specific student id. Here is my table as you see there are added 2 new rows getting another id. Here is my code and table:
<?php
$status = $_POST["status"];
$connect = mysqli_connect("localhost","root","admin","form");
if (!$connect) {
die('Connect error:'. mysqli_error());
}
$result = mysqli_query($connect, "INSERT INTO students (status) VALUES ('$status') ");
?>
idstudents |fname | lname| age | nationality | status
.....................................................
1 |Tom | Bern | 23 | American |
2 |Lily | Wayne| 24 | British |
3 |NULL | NULL | NULL| NULL | accepted
In order to update, you need an UPDATE statment, dont forget to add a student_id on the form. Consider this example: (Same Page Process).
<?php
$students = array();
$link = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_POST['submit'], $_POST['status'])) {
$status = $_POST['status'];
foreach($status as $student_id => $status_value) {
$stmt = $link->prepare('UPDATE students SET status = ? WHERE idstudents = ?');
$stmt->bind_param('ss', $status_value, $student_id);
$stmt->execute();
}
}
$query = mysqli_query($link, 'SELECT * FROM students');
while($row = $query->fetch_assoc()) {
$students[] = $row;
}
?>
<form method="POST" action="">
<?php foreach($students as $key => $value): ?>
<fieldset>
<p>
Name: <?php echo $value['fname'] . " " . $value['lname']; ?><br/>
Status: <b><?php echo ($value['status'] != '') ? $value['status'] : 'N/A'; ?></b><br/>
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="accepted" /> Accepted
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="rejected" /> Rejected
</p>
</fieldset>
<?php endforeach; ?>
<input type="submit" name="submit" value="Update" />
</form>
Note: Since you are using mysqli now, take advantage of parameterized queries. Dont directly use your $_POST values on the query.
The INSERT statement is meant to... Insert a new row. What you need is an UPDATE statement, to apply a value to a certain row, which you are going to select using their idstudents.
$status = $_POST["status"];
$studentid = $_POST["studentid"];
...
$result = mysqli_query($connect, "UPDATE students SET status = '$status' WHERE idstudents = $studentid;");
On a side note, always be careful when using $_POST (or other) values entered by the user, if this service is going to be used by other people, you might want to sanitize them before inserting them, to avoid potential security breaches.

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

Displaying user's SQL query using PHP

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>&pound$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

Categories