PHP MYSQL count two tables row and insert - php

I have two tables and I want to count how many 1 is in 1-2 table. If it is same amount than you can insert 1 if not than you can not insert 1 in to the table.
My code insert data even when it is equal or not:
<?php
$msg = '';
if(isset($_POST['rogzit_in'])) {
$barcode = $_POST['barcode'];
// Belépés ellenőrzése
if(!isset($_POST['barcode'])) {
$sql_barcodeInEll = "SELECT COUNT(barcode) FROM log_in WHERE barcode = '$barcode'";
$result_barcodeInEll = mysqli_query($dbCon, $sql_barcodeInEll);
$sql_barcodeOutEll = "SELECT COUNT(barcode) FROM log_out WHERE barcode = '$barcode'";
$result_barcodeOutEll = mysqli_query($dbCon, $sql_barcodeOutEll);
if(mysqli_num_rows($result_barcodeInEll) != $result_barcodeOutEll) {
$msg = '<h4 class="col-12 text-center mb-3 text-danger">Már bejelntkezett!</h4>';
}
}
if(isset($_POST['barcode'])) {
$sql_beszuras = "INSERT INTO log_in(barcode) VALUES ('$barcode')";
if(mysqli_query($dbCon, $sql_beszuras)) {
?>
<script type="text/javascript">
window.location = "home.php/";
</script>
<?php
}
}
}
?>
Thank you for the help!

Related

How to retrieve data after insert with new value in another table

<?php include('dbcon.php');
include('header.php');
//variable
$clientID='';
$billAmount='';
$arrear='';
$monthlyBill='';
$surcharge='';
//data add
$clientID=$_POST['clientID'];
$sqll = "SELECT `client`.`clientId` , (
`arrear` + `surcharge` + `monthlyBill`) AS 'billamount', (
FROM `billifno`
JOIN `client` ON `billifno`.`clientID` = `client`.`clientID` WHERE `billifno`.`clientID`='".$_POST["clientID"]."'";
$result = mysqli_query($con,$sqll);
// if ($result->num_rows > 0)
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$clientId = $row['clientId'];
$arrear = $row['arrear'];
$monthlyBill= $row['monthlyBill'];
$billAmount = $row['billAmount'];
$surcharge = $row['surcharge'];
}
//echo $billAmount;
$sql = "INSERT INTO `billIfno`
(`clientID`, `billAmount`,`arrear`, `monthlyBill`,`surcharge`) VALUES
('$clientID','$billAmount','$arrear','$monthlyBill','$surcharge')";
if ($con->query($sql)=== true)
{
echo "Recorded!!!";
}
else
{
echo "Not Recorded !!!";
}
$con->close();
?>
Hare I am taking some value and process it using query then again insert into billInfo table but it not inserting the new values like
If I echo billAmonu it print the correct value that is calculated by query bt that value is not inserting into database.

Print page output into a file

I have a reviewfile.php whereby i read the file uploaded and print results based on the conditions i coded.
I would like to know how to put my page results into a file.
This is so that i can download as pdf later on.
Below is my codes
if(isset($_POST['reviewFile'])){
if (isset($_POST['fileSelected'])){
$SelFile = $_POST['fileSelected'];
echo "<b>Filename:</b> $SelFile";
$query=$con->prepare("SELECT * from file where file_name = '$SelFile'");
$query->bind_result($file_id, $uid, $file_name, $file_size);
$query->execute();
$query->fetch();
$query->close();
$path = 'C:/xampp/htdocs/fwrule/fw/fileuploads/';
$file_to_get = $path.$SelFile;
$_SESSION['tmpfname'] = $file_to_get;
$_SESSION['excelReader'] = PHPExcel_IOFactory::createReaderForFile($_SESSION['tmpfname']);
$_SESSION['excelObj'] = $_SESSION['excelReader']->load($_SESSION['tmpfname']);
$_SESSION['worksheet'] = $_SESSION['excelObj']->getSheet(0);
$_SESSION['lastRow'] = $_SESSION['worksheet']->getHighestRow();
$_SESSION['highestColumn'] = $_SESSION['worksheet']->getHighestColumn();
//loop through each row of the worksheet in turn
for ($_SESSION['row'] = 3; $_SESSION['row'] <= $_SESSION['lastRow']; ++$_SESSION['row']) {
//read a row of data into an array
$rowData = $_SESSION['worksheet']->rangeToArray('A'.$_SESSION['row']. ':'.$_SESSION['highestColumn'] . $_SESSION['lastRow'], NULL, TRUE, FALSE);
//insert rows into database
$InsertData = $con->prepare("INSERT INTO file_data(id, file_id, no, name, source, destination, hit_counts, service, action, track, install_on, time, comment)
VALUES('', '$file_id', '".$rowData[0][0]."', '".$rowData[0][1]."', '".$rowData[0][2]."', '".$rowData[0][3]."', '".$rowData[0][4]."', '".$rowData[0][5]."', '".$rowData[0][6]."', '".$rowData[0][7]."', '".$rowData[0][8]."', '".$rowData[0][9]."', '".$rowData[0][10]."')") or die($con->error);
$InsertData->execute() or die ($InsertData->error);
$InsertData->store_result();
$InsertData->close();
}
if ($DuplicatedRows = $con->prepare("SELECT id
from file_data a
join (SELECT source, destination, hit_counts, service
from file_data
group by source, destination, hit_counts, service
having count(*) > 1 ) b
on a.source = b.source
and a.destination = b.destination
and a.hit_counts = b.hit_counts
and a.service = b.service;"))
{
$DuplicatedRows->bind_result($id);
$DuplicatedRows->execute();
$DuplicatedRows->store_result();
while($DuplicatedRows->fetch())
{
$rowNumforDuplicates = ($id+2);
$info1 = "Rule is duplicated";
echo "<tr>";
echo "<td>".$rowNumforDuplicates."</td>";
echo "<td>".$info1."</td>";
echo "</tr>";
}
$numRow = $DuplicatedRows->num_rows;//Checking rows in database
if ($numRow == 0)
{
echo "all perfect!";
}
//echo $numRow;
$DuplicatedRows->free_result();
$DuplicatedRows->close();
}
else{
?>
<html>
<script>
window.alert("Error message:: %s\n", $con->error");
</script>
</html>
<?php
}
if ($checkforAny = $con->prepare("SELECT id FROM file_data WHERE (source collate latin1_swedish_ci = 'any') or (destination collate latin1_swedish_ci = 'any')"))
{
$checkforAny->bind_result($id);
$checkforAny->execute();
$checkforAny->store_result();
while($checkforAny->fetch())
{
//row number in excel as the file is reviewed from line 3 onwards, hence 2 is added to the ID value
$rowNumforAny = ($id+2);
$info2 = "Source or Destination contains 'Any'";
echo "<tr>";
echo "<td>".$rowNumforAny."</td>";
echo "<td>".$info2."</td>";
echo "</tr>";
//echo "<br>";
//echo "The one with Any: $rowNumforAny";
}
$checkforAny->free_result();
$checkforAny->close();
}
else
{
?>
<html>
<script>
window.alert("Error message:: %s\n", $con->error");
</script>
</html>
<?php
}
if ($checkforComments = $con->prepare("SELECT id FROM file_data WHERE comment = '' "))
{
$checkforComments->bind_result($id);
$checkforComments->execute();
$checkforComments->store_result();
while($checkforComments->fetch())
{
$rowNumforComments = ($id+2);
$info3 = "Comment for rule is missing";
echo "<tr>";
echo "<td>".$rowNumforComments."</td>";
echo "<td>".$info3."</td>";
echo "</tr>";
}
echo "</table>";
//echo 'Save results as PDF';
$checkforComments->free_result();
$checkforComments->close();
}
else
{
?>
<html>
<script>
window.alert("Error message:: %s\n", $con->error");
</script>
</html>
<?php
}
if($DuplicatedRows == true && $checkforAny == true && $checkforComments == true)
{
//Truncate table "file_data" after each review so that data will not overlap.
$delAllData = $con->prepare("TRUNCATE file_data");
if ($delAllData->execute())
{
}
$delAllData->close();
}
else
{
?>
<html>
<script>
window.alert("Error message:: %s\n", $con->error");
</script>
</html>
<?php
}
}
if (!isset($_POST['fileSelected']))
{
?>
<html>
<script>
window.alert("Please select a file to review!");
window.location = 'https://localhost/fwrule/fw/filerecords.php';
</script>
</html>
<?php
}
}
You already have queries that find where problems EXIST, so why not use a NOT EXISTS...
select fd1.id
from file_data fd1
where not exists
(
SELECT 1 FROM file_data fd2 WHERE (source collate latin1_swedish_ci = 'any' or destination collate latin1_swedish_ci ='any') and fd2.id = fd1.id
)
and not exists
(
SELECT 1 FROM file_data fd3 WHERE comment = '' and fd3.id = fd1.id
)
and not exists
(
SELECT 1
from file_data a
join ( SELECT source, destination, hit_counts, service
from file_data
group by source, destination, hit_counts, service
having count(*) > 1 ) b
on a.source = b.source
and a.destination = b.destination
and a.hit_counts = b.hit_counts
and a.service = b.service
and a.id = fd1.id
)

Cant update, delete records or access database PHP

I have to create a program which allows users to delete an update lecturers from a lecturers table. For some reason the table which my program displays is not accurate(e.g older values than current table). And i cannot delete or update. I have been stuck on this for quite a while and apologies if it is a simple solution i am only a beginner.
<?php
//includes
include("CONFIG/connection.php"); //include the database connection
include("LIBRARY/helperFunctionsTables.php"); //include the database connection
include("LIBRARY/helperFunctionsDatabase.php"); //include the database connection
require_once("CONFIG/config.php"); //include the application configuration settings
?>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;" charset="UTF-8">
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo __CSS; ?>
</head>
<body>
<header>
</header>
<?php
include("PAGE_CONTENT/navigation.php");
//----------------MAIN SECTION----------------------------//
//========================================================//
echo "<section class='wide'>";
$table = 'lecturer'; //table to delete records from
$PK = "LectID"; //Specify the PK of the table
if (isset($_POST['delrecord'])) //if the form has been submitted
{
//DELETE query
$selectedID = $_POST['delrecord']; //get the ID of the record we want to delete from the form
$sqlDel = "DELETE FROM $table WHERE $PK='$selectedID'"; //create the SQL
if (deleteRecord($conn, $sqlDel)) //call the deleteRecord() function
{
echo "<h3>RECORD WITH PK=$selectedID DELETED</h3>";
} else {
echo "<h3 >RECORD WITH PK=$selectedID CANNOT BE DELETED</h3>";
}
//Re-display table with delete options
//Query string
$sqlData = "SELECT * FROM $table"; //get the data from the table
$sqlTitles = "SHOW COLUMNS FROM $table"; //get the table column descriptions
//execute the 2 queries
$rsData = getTableData($conn, $sqlData);
$rsTitles = getTableData($conn, $sqlTitles);
//check the results
$arrayData = checkResultSet($rsData);
$arrayTitles = checkResultSet($rsTitles);
//use resultsets to generate HTML tables with DELETE button
generateDeleteTable($table, $PK, $arrayTitles, $arrayData);
//close the connection
$conn->close();
} else if (isset($_POST['editrecord'])) //if the form has been submitted
{
echo "am in inside";
//DELETE query
$selectedID = $_POST['editrecord']; //get the ID of the record we want to delete from the form
$sqlEDIT = "SELECT FROM $table WHERE $PK='$selectedID'"; //create the SQL
if (deleteRecord($conn, $sqlEDIT)) //call the deleteRecord() function
{
echo "<h3>RECORD WITH PK=$selectedID DELETED</h3>";
} else {
echo "<h3 >RECORD WITH PK=$selectedID CANNOT BE DELETED</h3>";
}
include 'FORMS/newUserForm.html';
$lectFirstName = $_POST[lectFirstName];
$lectLastName = $conn->real_escape_string($_POST['fName']);
$sqlEdit = "UPDATE $table SET FirstName=lectFirstName, LastName=lectLastName WHERE $PK='$selectedID'";
if (deleteRecord($conn, $sqlEDIT)) //call the deleteRecord() function
{
echo "<h3>RECORD WITH PK=$selectedID DELETED</h3>";
} else {
echo "<h3 >RECORD WITH PK=$selectedID CANNOT BE DELETED</h3>";
}
//Re-display table with delete options
//Query string
$sqlData = "SELECT * FROM $table"; //get the data from the table
$sqlTitles = "SHOW COLUMNS FROM $table"; //get the table column descriptions
//execute the 2 queries
$rsData = getTableData($conn, $sqlData);
$rsTitles = getTableData($conn, $sqlTitles);
//check the results
$arrayData = checkResultSet($rsData);
$arrayTitles = checkResultSet($rsTitles);
//use resultsets to generate HTML tables with DELETE button
generateDeleteTable($table, $PK, $arrayTitles, $arrayData);
//close the connection
$conn->close();
} else //this is the first time the form is loaded
{
//display table with delete options
//Query string
$sqlData = "SELECT * FROM $table"; //get the data from the table
$sqlTitles = "SHOW COLUMNS FROM $table"; //get the table column descriptions
//execute the 2 queries
$rsData = getTableData($conn, $sqlData);
$rsTitles = getTableData($conn, $sqlTitles);
//check the results
$arrayData = checkResultSet($rsData);
$arrayTitles = checkResultSet($rsTitles);
//use resultsets to generate HTML tables with DELETE button
generateDeleteTable($table, $PK, $arrayTitles, $arrayData);
//close the connection
$conn->close();
}
echo "</section>";

php how to fetch multiple records and display in a query

I have a partner table and I need to send reply via SMS. So my table contains firm name, city, mobile and pincode. If someone sends me a pin code via SMS, I want to get back to the customer with the 2 or 3 records (Multiple). With this code I am able to send only one record.
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
$res= mysql_fetch_array($q);
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$mobile = $_GET['mobile'];
$reply_message = "Greeting. We will get back to you soon on the nearest Partner details.";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$mobile = $_GET['mobile'];
$reply_message = "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
Use while loop.
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
while($res= mysql_fetch_array($q))
{
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$mobile = $_GET['mobile'];
$reply_message = "Greeting. We will get back to you soon on the nearest Partner details.";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$mobile = $_GET['mobile'];
$reply_message = "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
}
Update with new requirement:
$mobile = $_GET['mobile'];
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
while($res= mysql_fetch_array($q))
{
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$reply_message .= "Greeting. We will get back to you soon on the nearest Partner details.";
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$reply_message .= "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
}
if (isset($reply_message) && $reply_message != '')
{
$reply_message1 = urlencode($reply_message);
if($res['pincode']=='')
{
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message1','$s')");//insert data in to table
}
// part 2
else
{
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message1','$s')");//insert data in to table
}
}
You are fetching only single record because you are not using any type of loop for getting multiple records.
Use while loop:
while($res= mysql_fetch_array($q))
{
//put your below inside the loop
}

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Categories