can any one guide me - php

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.

Related

The same barcode is unexpectedly inserting into my database

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

PHP: Delete || Confirm delete

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

Looping through dynamic input boxes and inserting into mysql database

I need your help with my form. I'm trying to build a dynamic forms, whereby a specific integer entered in a previous form sp1.php is used to display the number of input boxes.
The variables from the first forms are $state and $number. Then on the handling page sp2.php, the value of $number is put into a for loop to display the input boxes.
What I'm trying to do now is that the values entered into the tinput boxes are inserted into a mysql table.
The error I'm getting are
1) Undefined Index : DISTRICT
2) Invalid Argument supplied for foreach()
Please how can I make this work. Thank you.
My Code is below.. I'll be more than happy to show other parts of the code, if required.
Thank you.
<?php
$state=htmlspecialchars(($_POST['state'])) ;
$number = intval(($_POST['number']));
for ($i = 0; $i < $number ; $i++ ) {
echo "
<form action='sd2.php' method='post'>
<label for='name'>Districts</label>
<input type='text' name='district[]'>
<br/><br/>
</form>";
}
?>
<?php
foreach($_POST['district'] as $senatorial) {
$query = "INSERT INTO state ( `state_id`, `state`, `senatorial`)
VALUES (NULL, '".$state."', '".$senatorial."') ";
mysql_query($query) or die (mysql_error());
}
?>
This must work:
$count = count($_POST['district']);
for ($i=0; $i<$count; $i++){
$district = $_POST['district'][$i];
//do this
//do that
}

Saving content of form in array

I have a form where names from a SQL-database are listed. After each name there is a textfield for a grade. I want the grades and names to be saved in arrays. It already works with the names, but the array for the grades just gets filled with the content in the last textfield.
$Requete = "SELECT `vorname`, `nachname` FROM `lernende`";
$Result = mysql_query($Requete,$db);
$grade = array();
$vorname = array();
$nachname = array();
$counter = 0;
while($row = mysql_fetch_array($Result))
{
echo '<p>', $row["vorname"]," ", $row["nachname"], " ", '<label>Note: <input type="text" name="note"/></label></p>';
$grade[$counter] = $_POST['note'];
$vorname[$counter] = $row["vorname"];
$nachname[$counter] = $row["nachname"];
$counter = $counter + 1;
}
What is wrong with my code? I've just started learning php and have no idea how to solve this...
You hvae to change this line of code:
echo '<p>', $row["vorname"]," ", $row["nachname"], " ", '<label for="note-'.$counter.'">Note:</label> <input id="note-'.$counter.'" type="text" name="note[]"/></label></p>';
However, your code is not the finest I'd say. Start learning working with arrays as shown on http://php.net/array and start with clean HTML as described at http://de.selfhtml.org/ (since you are German speaking).
Give the grade fields different names, or name them as an array: <input name="note[]">
In your code you have $_POST['note'], which is getting repeated for each row,
for name field and note filed you should be attach $counter to distinguish these input fields.

PHP Multiple Dropdown Box Form Submit To MySQL (Part 2)

This is a continuation of the discussion at
PHP Multiple Dropdown Box Form Submit To MySQL
which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D
Given the following form:
<form action="form.php" method="POST">
<select name="colors[]" multiple="yes" size="2">
<option>Red</option>
<option>Blue</option>
</select>
<input type="submit" value="Go!">
</form>
how do I create new rows? The following script
foreach($_POST['colors[]'] as $color)
{
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
}
raises the error
Warning: Invalid argument supplied for foreach() in form.php on line ...
whereas the following
$colors = $_POST['colors[]'];
for ($i = 0; $i < count($colors); $i++)
{
$color = $colors[$i];
$sql = "INSERT INTO colors SET id = '$color'";
}
raises no errors but does no row creation.
What triviality am I missing here?
Use:
foreach($_POST['colors'] as $color)
No need to specify [] here, php knows that it is an array.
Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.
foreach($_POST['colors'] as $color) {
$id = mysqli_real_escape_string($link, $color);
$sql = "INSERT INTO colors SET id = '$id'";
if (!mysql_query($sql)) { // if the query encountered a problem.
die('Invalid query: ' . mysql_error());
}
}

Categories