Inserting value in table with the click of a button - php

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).

Related

How do I get my to only update whats selected?

There are two rows in my table called post. After pressing the button the table updates the row above it and if I click it again it updates that one it's supposed to.
If you press the button it adds 1 to the column. There are two rows, if you click the button for row 2 it will add one to row 1 then if you click it again it will update row 2. Or if you press it for one and try to press it for the other it will update the last one you clicked first and then update the one you wanted it to do.
//The loop echos the row out below
foreach($dbData as $post){
<form method="post" id="liketest" class="redirect" >
<button type="submit" form = "liketest" name="like" value= "'.$post["id"].'">
</button>
</form>
//If you press the button it is supposed to grab the id from the "post" (so the row id) and update count by adding 1
if (isset($_POST['like'])){
$post_id = $_POST['like'];
$result = $conn->query("SELECT * FROM likedpost");
if($result->num_rows == 0) {
$n = "count";
$stmt = $conn->prepare("UPDATE posts SET count = $n+1 WHERE id = $post_id ;");
$stmt->execute();
$stmt->close();
}
}
I expect it to update the row you clicked, but the actual result is it updating the row above it then the one you clicked.
You are violating the uniqueness of an element ID when you have a loop that doesn't generate a dynamic ID. So when you reference a different form with the form attribute, it will not know which one to use. Just drop the form references on your buttons altogether.
You should also be using bounded placeholders when you're using a prepared statement.
foreach ($dbData as $post){
echo '<form method="post" class="redirect" >
<button type="submit" name="like" value= "'.$post["id"].'">
Like this post!
</button>
</form>';
}
if (isset($_POST['like'])){
$stmt = $conn->prepare("UPDATE posts SET count = count + 1 WHERE id = ?");
$stmt->bind_param("s", $_POST['like']);
$stmt->execute();
$stmt->close();
}
<?php
if (isset($_POST['like'])) {
$sql = "SELECT * FROM likedpost";
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if ($count > 0) {
//performed you query
}
}
$sql1 = "SELECT * FROM likedpost";
$dbData=mysqli_query($conn, $sql1);
foreach ($dbData as $post) {
?>
<form method="post" id="liketest" class="redirect">
<button type="submit" form = "liketest" name="like" value="<?php echo $post['id']; ?>">Submit</button>
</form>
<?php
}
This is simple logic you can apply in $count variable you will get number of liked post and after that you can used that $count variable count+1 to update in another table (this is mysqli Procedural way)

Select elements from 2 different tables to put in a php loop

I'm making a web site for a business and in the "car list" I would like to take information from 2 tables of my data base, one for the car info (name, price...) and the other one for the images URL table.
Example of my code:
$mysqli = new mysqli("localhost","root","","database") or die("1");
$sql = "SELECT * FROM cars WHERE type= '".$cartype."'";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<table>
<tr>
<td> HERE IMAGE URL FROM TABLE 2 </td>
<td> <?php echo $row['name']; ?> INFO FROM TABLE 1 </td>
</td>
</table>
<?php
}
}
How can I connect to table 2 and put the info in my while loop?
Thanks a lot.
You are going to have to join your two database tables in your select query. To do that you need an id in your photos table that links it to your cars table.
Example:
$sql = "SELECT name,url FROM cars,photos WHERE cars.id = photos.car_id AND type= '".$cartype."'";
Then use
$row['name']; $row['url'];

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.

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

primary key and foreign key in 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");

Categories