PHP problem with insert into database in while loop - php

i try to write a website for library as an exercise. I have while loop to display all books in my database. If user is logged in and state(stan) of book(ksiazka) is free(Wolny) it shows button under book. After clicking it takes all free books to database and update their state as hired not only that one which user want. Here is the code, thanks.
$findbook2 ="select ksiazka.id_ksiazka, ksiazka.tytul, ksiazka.id_stan, autor.id_autor, autor.imie_autor, ksiazka.rok_wydania, autor.nazwisko_autor, stan.id_stan, stan.nazwa_stan FROM ((ksiazka inner join autor ON ksiazka.id_autor = autor.id_autor) inner join stan ON ksiazka.id_stan = stan.id_stan);";
$stan = mysqli_query($connect, $findbook2);
while($row = mysqli_fetch_array($stan))
{
echo "Tytuł:" . " " .$row['tytul']." ". "Autor:" . " " . $row['imie_autor']." ". $row['nazwisko_autor']. " ". "Rok wydania" . " ". $row['rok_wydania'] . " ". "Stan ". $row['nazwa_stan']. " ";
if(isset($_SESSION['id_czytelnik'])){
if($row['nazwa_stan']=='Wolny'){
echo '<form method = "GET" action = "ksiazki.php">';
echo '<input type = "submit" name = "submit" value = "Wypożycz"/>';
echo '</form>';
if(isset($_REQUEST['submit'])){
$id_czytelnik = $_SESSION['id_czytelnik'];
$id_ksiazka = $row['id_ksiazka'];
$data_oddania = date('Y-m-d', strtotime('+30 days'));
$wstaw_ksiazke = "INSERT INTO `wypozyczenie`(`id_wypozyczenie`, `id_czytelnik`, `id_ksiazka`, `id_pracownik`, `data_wypozyczenia`, `data_oddania`) VALUES ('','$id_czytelnik','$id_ksiazka',2,NOW(),'$data_oddania')";
if(mysqli_query($connect, $wstaw_ksiazke)){
$update = "Update ksiazka set id_stan = 3 where id_ksiazka = '$id_ksiazka'";
if(mysqli_query($connect, $update)){
echo "Wypozyczyłeś książkę";
}
}
}
}
}
echo "</br>";
}

Consider the statement if(isset($_REQUEST['submit'])) which is always true inside your while loop after clicking submit as it is not unset anyway.It causes repeated execution of a statement while the Array is not empty.

Related

How to enable a log just before the php query

I am trying the approach of 'adding a log just before the php query'; in effort to achieve the ability to print a 'time stamp' when my mySQL database has been updated.
my queries look like this.
require_once('include/connect.php');
$q = $_GET['q'];
//echo $q;
//$plan=substr($q,0,4);
//$spec=substr($q,4);
list($plan, $ptype, $spec) = explode('_', $q);
//echo $plan . ", " . $spec;
//$query="SELECT vphp.tbl_provider_types.`TYPE` from coolDB.tbl_provider_types where vphp.tbl_provider_types.".$q." = 'Y';";
$query= "SELECT tbl_sourcespecheader.specID, coolDB.tbl_sourcespecheader.Specialty_Header from vphp.tbl_provider_types left join coolDB.tbl_sourcespecheader on coolDB.tbl_provider_types.ID = coolDB.tbl_sourcespecheader.TypeID where coolDB.tbl_provider_types.ID = " . $spec . " and coolDB.tbl_sourcespecheader." . $plan . " = 'Y';";
$result = mysqli_query($connection, $query);
//Populate result in HTML which will be returned via AJAX
echo "<h4>Please select from these " . $ptype . " specialties:</h4>";
echo "<select id='type' multiple='' name='specialty'><option selected="selected" value="nospec"></option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['specID'] . "'><a href='#' id='" . $row['specID'] . "' onclick='getSelected(this.id);return false' style='text-decoration: none'>" . $row['Specialty_Header'] . "</a></option>";
}
echo "</select>";
//Close database connection
mysqli_close($connection);
Better use triggers. You need to create log table to be able to insert all data you needed. Below is the example.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
If you are using phpMyadmin. Go to that and find the trigger menu. There you can create triggers.

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

PHP Use array results to complete MySQL query and add results to existing array

I solved the problem with both the foreach loop stopping after the first iteration, as well as it not writing to the array by adding true to the json_decode. I was unaware that that changed it from object oriented to associated.
include '/var/www/html/api/apitoken.php';
include '/var/www/html/api/secrets.php';
$data = file_get_contents('/var/www/html/api/shOrders.json'); // put the contents of the file into a variable
$shOrders = json_decode($data, true);
$con = mysqli_connect("127.0.0.1",$user,$pass,"api") or die('Could not connect: ' . mysqli_error());
$a=0;
foreach($shOrders['varID'] AS $varID) {
$sql_statement= " SELECT invTrack AS invTrack, varID AS varID, varSKU AS varSku, revelSku AS revelSku, revelInvID AS revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product, i.invID AS invC, pr.qty AS QTY
FROM shopifyProd sp
LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
LEFT JOIN inventory i ON pr.product = i.prodID
WHERE varID =" . $varID . " ; ";
//connect to mysql db and process the statement
$result = mysqli_query($con,$sql_statement);
//var_dump($sql_statement . "<br><br>");
while($row = mysqli_fetch_assoc($result)) {
echo "varID: ";
print_r($row['varID']);
echo "<br>";
if($varID == $row['varID']) {
//set correct invID for product in revel
if (!$row['invC']) {
$revInvID = ( (int) $row['revelInvID']);
}else{
$revInvID = ( (int) $row['invC']);
}
//calculate qty to change in revel
if(!$row['QTY']) {
$changeQTY = $shOrders['soldQTY'][$a];
}else{
$changeQTY = ($row['QTY'] * $shOrders['soldQTY'][$a]);
}
echo $varID . " RESULTS! -- ";
print_r("varSku: " . $shOrders['varSku'][$a]);
echo ", ";
print_r("revelInvID: " . $row['revelInvID']);
echo ", ";
print_r("soldQTY: " . $shOrders['soldQTY'][$a]);
echo ", ";
print_r("ingredient: " . $row['ing']);
echo ", ";
print_r("Product: " . $row['product']);
echo ", ";
print_r("invC: " . $revInvID);
echo ", ";
print_r("changeQTY: " . $changeQTY);
echo "<br><br>";
$shOrders['revProdID'][$a] = ( (int) $row['product']);
$shOrders['revInvID'][$a] = ( (int) $revInvID);
$shOrders['changeQTY'][$a] = ( (float) $changeQTY);
if (!mysqli_query($con, $sql_statement)) {
print_r(mysqli_error_list($con));
echo "<br>";
mysqli_close($con);
}
}
}
$a++;
set_time_limit ( 30 );
}
echo "<pre>";
print_r($shOrders);
echo "</pre>";
var_dump out your query just before you run it, Are all the expected parameters there? Try running that in your local db tool (mysql workbench, phpmyadmin), does it do what you like?
var_dump out the variables at each step of the way and die (or alternatively use a debugger to step through the code 1 line at a time), to see what is happening.
It doesn't look like you've declared $varID above the query.
I think you need to move
foreach($shOrders->varID AS $varID) {
above the $sql_statement = ... line.

Possible To Use Insert Query In Fetch Array

I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.

Running if database row number is less than 10

I'm trying to make a function work only if the number in the row 'click' in my datbase is less than 10. This is what I have right now: I put the echo in there just to see if the condition is working or not.
<?php
include'connect.php';
$result = mysqli_query($con,"SELECT id, link_name, click FROM clicks");
while($row = mysqli_fetch_array($result))
{
if ($row['click'] < 10) {
echo $row['id'] . " " . $row['link_name']. " " .$row['click'];
echo "<br>";
}
}
mysqli_close($con);
?>
try;
$result = mysqli_query($con,"SELECT id, link_name, click FROM clicks WHERE click<10");
while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['link_name']. " " .$row['click'];
echo "<br>";
}
mysqli_close($con);
?>
Why don't you use a where clause in your query?
$result = mysqli_query($con,"SELECT id, link_name, click FROM clicks
where click <10");

Categories