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)
Related
Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
I"m trying to display names that connected to the same table.
There are 3 different DB tables:
Tables
Guests
Info
First I get the data from the "Table" to get the table id.
Than I get the data from the "Info" table to figure which guests are connected to the table id so I get their id's (can be multiple id's).
And last I get the name of every guest by it's id.
My issue is that I can only get the final name I'm expecting and not all names that are connected to the same table.
The last result needs to display each table and every name that connected to table.
PHP:
$sql_e1 = "SELECT `tid` FROM `table`";
$result_e1 = $con->query($sql_e1);
if ($result_e1->num_rows > 0) {
$i = 0;
while($row0 = $result_e1->fetch_assoc()) {
$table_id = $row0['tid'];
$array[$i]['table_id'] = $table_id;
$sql_e2 = "SELECT `id` FROM `info` WHERE `tid`='".$table_id."'";
$result_e2 = $con->query($sql_e2);
if ($result_e2->num_rows > 0) {
while($row2 = $result_e2->fetch_assoc()) {
$guest_id = $row2['id'];
$array[$i]['guest_id'] = $guest_id;
$sql_e3 = "SELECT `name` FROM `guests` WHERE `id`='".$guest_id."'";
$result_e3 = $con->query($sql_e3);
if ($result_e3->num_rows > 0) {
while($row3 = $result_e3->fetch_assoc()) {
$array[$i]['name'] = $row3['name'];
}
}
}
}
$i++;
}
}
$counter = 0;
HTML:
<?
if (isset($i)) {
while ($counter < $i) {
include 'infodialog.php';
?>
<div class="<? echo $array[$counter]['table_id']; ?>">
<p><? echo $array[$counter]['name']; ?></p>
</div>
<?
$counter++;
} } ?>
If you want to get multiple names in array your code should be:
$array[$i]['name'][] = $row3['name'];
Or according guest ids code should be
$array[$i][$guest_id]['name'][] = $row3['name'];
This will get all the names but you have to change your HTML code according array.
Another solution besides Rohit Rasela's is using JOINS. JOINS will be a much better solution in the long run especially when you start adding a lot of data and speed is important. It's been a while since I've done PHP and MySQL and I haven't tested this but it should work I believe:
MySQL:
SELECT
guests.name as GuestName,
table.tid as TableId,
info.id as InfoId
FROM table AS table
JOIN info AS info ON info.tid = table.tid
JOIN guests AS guests ON guests .id = info.[guest_id_column_name]
This will return a row for each match it finds when it goes through each table and you'll be able to loop through and access the GuestName, TableId and InfoId for each match. If you don't care about the table ids, you can leave them out in the SELECT list. You can add ORDER BY if the order matters.
HTML loop:
while ($row = $result->fetch_assoc()) {
<div>Guest name: <php echo $row['GuestName']; ?></div>
<div>Table Id: <php echo $row['TableId']; ?></div>
<div>Info Id: <php echo $row['InfoId']; ?></div>
}
You can get more information on JOINs at https://www.w3schools.com/sql/sql_join.asp
I seem to be running into this issue often, usually for checking to see if a $_GET['id'] actually exists in my database before running another query, related or not to the id being received.
If a record exists with the same id, then I show the HTML, e.g.:
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
...
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
The above works, but let's say that I want to perform another unrelated query between my opening/closing form tags; would it be proper to simply do something like this, which I would consider a nested query:
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
<?php
$q = "SELECT example FROM somewhere";
$r = #mysqli_query($dbc, $q);
if ($r) {
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['example'];
}
}
} else {
echo 'Query failed';
}
?>
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
Or maybe create a boolean, like so:
$id_status = 0;
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
$id_status = 1;
}
}
mysqli_free_result($r);
if ($id_status) { #Run another query
...
}
I currently have a problem when it comes to requiring two separate query results for one task: (1) generating inputs from another table, (2) displaying the current values, (3) checking to see what input that has been generated matches the current value, e.g.:
$q = "SELECT id, food FROM restaurants";
$q = "SELECT favFood FROM people WHERE id = 1"; #favFood is equal to the id of food
...
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
?>
#generate all food from table, make favFood the current selected input
<input type="radio" name="yum" value="<?php echo $row['id']; ?>" />
<?php
}
So as you can see, I am having trouble when it comes to unrelated queries; the last example would probably work with a UNION or something, but i'd have a bunch of repeated rows displaying favFood, so it doesn't feel right, e.g.:
favFood | id | food
1 | 1 | Pizza
1 | 2 | Burgers
1 | 3 | Monkey Brains
Before I end this, I just want to say that I have made an attempt to use mysqli_multi_query, but I most likely did something wrong; i'm not even sure if it would work in this case, or what it does exactly.
Thanks!
If you want to check whether a record exists multiple times in your code, I suggest to create a function which returns a bool.
function record_exists($dbc, $q){
$state = false;
if($r = #mysqli_query($dbc, $q)){
if(mysqli_num_rows($r) == 1){
$state = true;
}
mysqli_free_result($r);
}
return $state;
}
$q = "SELECT id FROM stuff WHERE id = $id";
if(record_exists($dbc, $q)){
echo 'Yay, it exists';
}
Then if you want to SELECT some fields from a table but the filter depends on a value from another table, you could JOIN two tables in the query like so:
SELECT restaurants.id, restaurants.food
FROM restaurants
JOIN people ON restaurants.id = people.favFood
WHERE people.id = 1
Now you only SELECT the fields you want from table restaurants and filter them on a person id from the table people.
Two reasons why you've got such a problem
You are doing A LOT of useless stuff.
no one needs you "query failed" statement.
num rows check is also superfluous
most of the code you write is just repetitions
Like PHP users from the last century you are mixing database calls with HTML output. Now you see that the term "spaghetti code" was coined for a reason.
Your database related code rewritten with simple mysqli wrapper:
$rows = [];
$found = $db->getOne("SELECT id FROM stuff WHERE id = ?i", $id);
if ($found) {
$rows = $db->getAll("SELECT example FROM somewhere");
}
Now you can proceed to HTML output, either inline or (better) by including a template
?>
<?php if ($rows): ?>
<form method="post">
<?php foreach ($rows as $row): ?>
<?=$row['example']?>
<?php endforeach ?>
<input type="submit" value="Submit" />
</form>
<?php else: ?>
No records
<?php endif ?>
I've had this problem for a little while and probably didn't ask the question properly last time. Having dabbled again I'm still very much confused and stuck.
I have a MySQL table that I list out a series of checkboxes based on values in this (around 200).
I have another MySQL table where a user will store their preferences, when the list loads I wish for the items that the user had previously selected in the second MySQL table to be checkboxes that have the check mark already assigned indicating previous choice. If you could please take a look at the following and point me in the right direction I'd be grateful.
$result = mysql_query("SELECT `car` FROM `carlist` ORDER BY variety ASC");
$result2 = mysql_query("SELECT `car` FROM `lists` WHERE `username` = 'Palendrone' ORDER BY variety ASC");
if (!$result) {
die("Query to show fields from table failed");
}
if (!$result2) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
}
$fields_num2 = mysql_num_fields($result2);
for($j=0; $j<$fields_num2; $j++)
{
$field2 = mysql_fetch_field($result2);
}
while($row = mysql_fetch_row($result))
{
while($row2 = mysql_fetch_row($result2))
{
if("$row2[0]" <> "$row[0]")
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
} else
{?><input type="checkbox" value="<?php echo "$row[0]"?>" name="<?php echo "$row[0]"?>" checked="yes" id="<?php echo "$row[0]"?>">
<label for="<?php echo "$row[0]"?>"><?php echo "$row[0]"?></label>
<?php
}
} /* end while */
} /* end while */
I figured the first While loop to load the main 200 items in, then for each input in that table it cross checks against the users selection table in the second while loop, in that loop I have the if statement working in reverse order so as not to check it then uncheck it.
I was pointed in the way of starting from scratch last week by another user on here, although I've started going through some tutorials I kinda need to get this last part of my project nailed...
I would suggest changing your query strategy - use only one instead of two. You can check the value of second member of select list - lists.car from result of query below for null value. If it is null then checkbox is not selected otherwise it is (it is present in second table).
$result = mysql_query("SELECT `carlist`.`car`, `lists`.`car` FROM `carlist` left join `lists` on (`carlist`.`car` = `lists`.`car` and `lists`.`username` = 'Palendrone') ORDER BY `carlist`.variety ASC");
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");