This is a code for inserting the barcode into a database but if the same barcode exists in the database, I don't need this to be inserted same again, so I coded like this but still, the same barcode is inserting in my database. What the error in this code?
I am using mysqli and Bootstrap to show the errors in the page, the page is executed from another page called product.php via ajax and it is showing in another page called showuser.php as it gets updated in a table which should give the output
<?php
include('conn.php');
if(isset($_POST['add'])){
$proname=$_POST['product'];
$bar=$_POST['barcode'];
$war=$_POST['warranty'];
$gar=$_POST['guarranty'];
$amount=$_POST['amount'];
$id = $_POST['cusid'];
$date = $_POST['date'];
$check = "SELECT * FROM warranty_update WHERE battery_serial = '$bar'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
?>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<h3 align="center"><i class=" glyphicon glyphicon-warning-sign"></i><br>
<br>
Sorry Barcode Already Been Inserted !<br><br>
Please Go Back</h3>
<?php } else {
$datesplit = explode("-",$date);
$warranty = $datesplit[0];
$guarante = $datesplit[0];
$day = $datesplit[1];
$month = $datesplit[2];
$fdate = strtotime($date);
$Gm=strtotime("+$gar Months",$fdate);
$wm=strtotime("+$war Months",$Gm);
$m1=date("Y-m-d", $Gm) ;
$m2 =date("Y-m-d", $wm) ;
$today = date("Y/m/d");
$expiry_warranty = $m2;
$expiry_guarante = $m1;
//mysql_query("INSERT INTO `cus_reg`(`reg_id`, `name`, `mobile`, `battery_serial`, `model`, `date`, `reg_by`, `warranty_expiry`, `waranty_span`,`guarantee_expiry`, `g_span`) VALUES (NULL,'$name','$mobile','$battery_serial','$vehicle_num','$date','$regby','$expiry_warranty', '$wmonth', '$expiry_guarante', '$gmonth')")==true or die(mysql_error);
//mysql_query("INSERT INTO `warranty_update`(`wa_id`, `cus_reg_id`, `new_barcode`, `date`) VALUES (NULL,LAST_INSERT_ID(),'$battery_serial','$today')");
mysqli_query($conn,"INSERT INTO `warranty_update`(`wa_id`, `reg_id`, `battery_serial`, `model`, `date`, `warranty_expiry`, `waranty_span`, `guarantee_expiry`, `g_span`, `amount`) VALUES (NULL,'$id','$bar','$proname','$today','$expiry_warranty','$war','$expiry_guarante','$gar','$amount')");
mysqli_query($conn,"INSERT INTO `replacements`(`r_id`, `reg_id`, `wa_id`, `new_barcode`, `date`) VALUES ('NULL','$id',LAST_INSERT_ID(),'$bar','$today')");
?>
<!--header("refresh:1;url=home.php");-->
<h3 align="center"><i class=" glyphicon glyphicon-warning-sign"></i><br>
<br>
Data Successfully Inserted !
<?php }
}
?>
Not entirely sure, but you should check you array like this for entries:
if (count($data) > 0)
The best way to do this is defining a unique constraint on barcode via SQL.
Anyway I think that you are valuating the condition in an erroneous mode.
$data is an array, so you should check his size with: sizeof.
so: if(sizeof($data) > 1) { .... }
Related
I need a help with my code; somehow my code creates two rooms (it inserts two rows into a table at once), I don't know why.
(I need to require an id for every insert to know in which house we create a new room. My database contains table 'house' and table 'room'. Table 'room' has a field 'house_id' which is a foreign key with a field 'id' in table 'house'.)
That is my php page:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
and that is my html template with form:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>
It inserts 2 rows because of your using the query function twice:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
So you'll need to change that conditional statement to:
if ($result) {
By the way, use a prepared statement, it's safer than real_escape_string():
https://en.wikipedia.org/wiki/Prepared_statement
You are inserting it twice
first here:
// run the query to insert the data
$result = mysqli_query($con, $query);
then here:
// check if the query went ok
if ( $con->query($query) ) {
Remove the first one and you should be fine, or check on the result of the first one and remove the second one.
Not 100% certain, but it looks like you run INSERT query twice. Once here:
$result = mysqli_query($con, $query);
and once a moment later when you try to check for something. you inadvertently use the OOP style when you are apparently trying to check for something
if ( $con->query($query) ) {
I'm trying to pass a value which is input into a box on one Php page (itinerary.php) into another Php page ('submit.php') so it can, from there, be saved into a database. But I can't quite figure out how to get it across. I've tried using GET as you can see from code below, but I am already using a GET statement to receive and acknowledge another value from that very same page 'submit'. I guess I am overcomplicating it, but my knowledge of Php is still pretty limited at this stage so any ideas would be appreciated!
This is an extract from the itinerary.php file (it sits within a Bootstrap/Html framework. Note the entry which contains the input box for the sequence number).
<h3><br>YOUR ITINERARY</h3>
<?php
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<table><tr><th colspan="5">LOCATIONS IN YOUR ITINERARY</th></tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<br><td>{$row['loc_name']}</td></tr><br>
<td>{$row['loc_desc']}</td>
<td><p>Seq. No</p><input type=\"text\" size=\"3\" name=\"sequence\" value=????????>NOT SURE WHAT TO ADD INTO THIS LINE TO RETAIN THE INFO THAT IS INPUT</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
</tr><br></table>";
}//while
print_r($_SESSION);
mysqli_close($db);
}//if
else {echo '<p><br>Your itinerary is empty.<br></p>';}
echo '<br><p>
<a href=submit.php?submit>Save itinerary</a>
<a href=clear_itin.php?clear>Clear itinerary</a>
Your details
Logout
</p>';
?>
And this is where I am trying to receive it and then use it in a SQL command to add to the database. (Again, this is within a Bootstrap framework)You can ignore the first SQL Insert statement as it is passing other info in successfully anyway..
<div class="row">
<div class="col-md-9">
<?php
if (isset($_GET['sequence'])){
$sequence = $_GET['sequence'];
}//if
if (isset($_GET['submit'])){
$query = "INSERT INTO itineraries (user_id, date_created) VALUES (".$_SESSION['user_id'].", NOW())";
$result = mysqli_query($db, $query);
$itinerary_id = mysqli_insert_id($db);
$retrieve_locs = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $id=>$value)
{$retrieve_locs.=$id.',';}
$retrieve_locs = substr($retrieve_locs, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $retrieve_locs);
//Store items in itin_locs db
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)){
//This is the command I have been trying to use, commented out. The second one below this works fine, but obv doesn't input a sequence number.
//$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id, sequenceNo) VALUES ($itinerary_id, ".$row['loc_id'].", $sequence)";
$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id) VALUES ($itinerary_id, ".$row['loc_id'].")";
$insert_result = mysqli_query($db, $insert_locs);
echo mysqli_error($db);
if ($insert_result === FALSE) {
die("Query failed!" . mysql_error() . $insert_locs);}
}//while
mysqli_close($db);
echo"<p>Your itinerary is saved!. Itinerary number is #".$itinerary_id."</p><br>";
$_SESSION['itinerary']= NULL;
echo '<p>
Your details
Logout
</p>';
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
?>
Use a form on your HTML page to hold all the input fields in the table.
Also instead of anchor "a" tag use a submit button to submit the form to other page.
Use some thing like:
Send value of submit button when form gets posted
I'm new in PHP language and i doing a task now. I have to take two queries with onclick function. When i click "Best rate" to call the rows from the table ordered by rate and when i click "All reviews" to call them by date created. Do i need to use ajax or there is better way to do it ?
<?php
$posted = false;
if(isset($_POST['add']))
{
$posted = true;
$email = $_POST['email'];
$name = $_POST['name'];
$rate = $_POST['rate'];
$comment = $_POST['comment'];
$dth = date("Y-m-d H:i:s");
$q = "INSERT INTO reviews(email, name, rate, comment, date_created) VALUES ('$email', '$name', '$rate', '$comment', '$dth')";
$k = mysqli_query($con,$q);
}
?>
<body>
<p>Best rate</p><?php
$select_reviews = "SELECT comment, rate FROM reviews ORDER BY date_created DESC LIMIT 4" or die("Не може да изпълни заявката");
$run_reviews = mysqli_query($con, $select_reviews);
while ($review = mysqli_fetch_assoc($run_reviews)){
$post_review = $review['comment'];
$post_rate = $review['rate']
?>
<div class='comment'> <?php echo $post_review; ?></div>
<div class='rate'> <?php echo $post_rate; ?> </div>
<div>-----------------</div>
<?php
}
?>
Here is the code where i make the query and where the reviews are ordered by date. I want to make it when i click "Best rate", the reviews to reorder by rate.
You actually don't need AJAX for this one.
Ajax would be better if your button was "Best Rates of Last year" or "View More Rates" ---
But since you only want the data to be re-ordered, you really don't need to use AJAX...
You can simply re-order the "rate" values with javascript -!
insert below code on a php file like SelectByRate.php
<?php
$select_reviews_By_Rate = "SELECT comment, rate FROM reviews ORDER BY rate DESC LIMIT 4" or die("Не може да изпълни заявката");
$run_reviews = mysqli_query($con, $select_reviews_By_Rate);
while ($review = mysqli_fetch_assoc($run_reviews)){
$post_review = $review['comment'];
$post_rate = $review['rate']
?>
<div class='comment'> <?php echo $post_review; ?></div>
<div class='rate'> <?php echo $post_rate; ?> </div>
<div>-----------------</div>
load this code for php file and then load the result with ajax
$('button.showByRate').click(function(){
$.get('your SelectByRate.php file url',{DataName:DataValue},function(data){
//insert your data on page with javascript
//for example use this
$('p.showByRate').html(data);
}
});
example for use ajax
I had successfully pulled out students details that is name , class , section .. as it is a attendance management system. But i facing problem in saving all the values ie Name , Class, Section , Status (P/A) in my database. Bellow the attendance submit code ... please guide me.
// showing values
<input type="hidden" id="" name="locationID[]"/><?=$i;?></div></input>
<input type="hidden" id="" name="name[<?=$name;?>]"/><?=$name;?></input>
<?php
include('config.php');
#session_start();
$sessionName = $_SESSION['NAME'];
$date = date('d-m-y');
$loc= $_POST['locationID'];
$name = $_REQUEST['name'];
$status = $_POST['status'];
$class = $_POST['class'];
$section = $_POST['section'];
for( $i = 0; $i < count($loc); $i++ )
{
$sql = "INSERT INTO tbl_attendence (fld_studentname,fld_status,fld_class,fld_section,fld_date,fld_takenby)
VALUES ('$name','$status','$class','$section','$date','$sessionName')";
//echo $sql; exit;
mysql_query($sql);
}
?>
After running this code i am getting Array, in all columns ... please guide me...
Assuming that you are return arrays of values in POST, a possible solution could be
$sql = "INSERT INTO tbl_attendence (fld_studentname,fld_status,fld_class,fld_section,fld_date,fld_takenby)
VALUES ('{$name[$i]}','{$status[$i]}','{$class[$i]}','{$section[$i]}','{$date[$i]}','{$sessionName[$i]}')";
Suggestions:
1. Avoid your code from SQL Injection
2. Use XDebug or use print_r() whenever you see this kind of problem of Array instead of values to debug properly what is the problem.
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..