This question already has answers here:
Use bound parameter multiple times
(5 answers)
Closed 3 years ago.
I now already create a table called' factory. In his table, there are two columns which is Fac_ID (Primary Key, Varchar) and Fac_Name (Varchar). Let say if I want to add a new factory. E.g F09, then the Fac_ID and Fac_Name also insert with F09.
I just only key in F09 at Fac_Name and after I click button 'add', it will save F09 at Fac_ID and Fac_Name. Below is my current PHP code
<?php
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$Fac_Name = $_POST['Fac_Name'];
$Fac_ID = $_POST['Fac_Name'];
// checking empty fields
if(empty($Fac_ID)) {
if(empty($Fac_ID)) {
echo "<font color='red'>Name field is empty.</font>
<br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go
Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$sql = "INSERT INTO users(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
$query = $conn->prepare($sql);
$query->bindparam(':Fac_Name', $Fac_Name);
$query->bindparam(':Fac_Name', $Fac_ID);
$query->execute();
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
You cannot use the same bind parameter twice, so would suggest to do the following:
$sql = "INSERT INTO users(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Id)";
$query = $conn->prepare($sql);
$query->bindparam(':Fac_Name', $Fac_Name);
$query->bindparam(':Fac_Id', $Fac_ID);
$query->execute();
It also makes more sense as the variable you put in is also called $Fac_ID.
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I am trying to update my database through a input box in html. So far everything works exception of the name. It wont update the name if its actual characters such as 'toys'. It will however update if I type in numbers such as 45634. My database value for "name" is varchar(15).
Here is my code to update the name in the database.
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `item` SET `name`=$data[4] WHERE itemID = $data[0]";
try{
$update_Result = mysqli_query($conn, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($conn) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
My HTML box is here just the name part of it
<input type="text" name="name" placeholder="name" value="<?php echo $name;?>"><br><br>
and this is how I store the value name there is others but they work fine only having trouble with the name
function getPosts()
{
$posts = array();
$posts[4] = $_POST['name'];
return $posts;
}
If name type is VARCHAR, you have to put string into it, not integer. Try to change SET `name`=$data[4] into SET `name`='".$data[4]."'.
I am developing a platform that allows me to enter presences at an event and I am stuck in one place. How can I load a series of checkboxes in order to change the user ID for each item?
A practical example, I have a table containing the name of all the people and next to it a checkbox once pressed submit php must upload the data for each user to the db.
Below the html form and the php script that manages the upload to the db.
'''php
<?php
$query = "SELECT * FROM utenti";
$ris = mysqli_query($conn, $query);
//$dati = mysqli_fetch_array($ris);
while($row = mysqli_fetch_assoc($ris)){
echo "<tr><td>".$row['nome']."</td>";
echo "<td>".$row['cognome']."</td>";
echo "<td>".$row['squadra']."</td>";
echo "<td>
<input type='checkbox' name='presenza' data-toggle='toggle' data-onstyle='success' data-offstyle='danger' data-on='Presente' data-off='Assente' value='1'>
</td></tr>";
}
'''
if (isset($_POST['submit'])){
if(!empty($_POST['presenza'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['presenza'] as $selected){
echo $selected."</br>";
$sql="INSERT INTO presenze(id_utente,settimana,presenza) VALUES ('1','1','$selected')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
}
}
'''
One of the way to get relationship between a user and a checkbox is to use user ID (or whatever unique identifier you have in your tables structure) in checkbox name e.g.:
"<input type='checkbox' name='presenza_" . $row['user_id'] . "'>"
Then on the backend you can iterate over all post params with presenza_ prefix and get user ID from it.
So your code will be a bit more sophisticated:
foreach($_POST as $param_key) {
// working only with params started with presenza_
if (0 !== strpos($param_key, "presenza_")) {
continue;
}
$presenza_parts = explode("_", $param_key);
$user_id = (int)$presenza_parts[1];
}
Keep in mind that checkbox field sends only value if it's switched on and sends nothing if it's switched off.
Hello iam trying to create a disciplinary system. i created a table where accused and the victim had to put their information. I have created another table for report and i have failed to combine all the information given in the first table into one doc file so that i can use it in report. I need help?
enter code here
if(isset($_POST['call'])){
$accused = $_POST['dss'];
$report= $_POST['cas'];
$action = $_POST['uect'];
$u_cat = intval($_POST[id]);
if($report ==''){
echo "<font color='Green'><b>Please fill in the Report!</b></font>";
}else{
if($u_cat) $insert = "update discip_report set accused_student='$accused', case='$report', action_taken='$action' where id='$u_cat'";
else $insert = "insert into discip_report(accused_student, report, action_taken, date) values('$accused','$report', '$action', NOW())";
$run = mysql_query($insert);
if ($run) {
echo "<font color='Green'><b>The Category was added</b></font>";
}else{
echo "<font color='Green'><b>The Category was not added</b></font>";
}
}
}
?>
My code:
<?php
$name = $_POST["name"];
//establishing connection through PDO
require("database.php");
try{
//querying the firstname data from the people table
$sql = $conn->query("SELECT firstname FROM people");
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
//looping through the array of firstname and echoing it out if it equals to the user input of name. else just echo out sorry no match
while($theRow = $sql->fetch(PDO::FETCH_ASSOC)){
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) && isset($_POST['name']) ){
echo $theRow['firstname'] . "<br />";
}else {
echo 'Sorry no match';
exit;
}
}
?>
the require database.php is just establishing connection to my database using PDO.
I just have 2 rows in my database with
'firstname' of
Jack
Bob
and if in my input field anyone types one of those 2 names php will echo out that name from the people table in the database. Very simple but the only problem I am having is on my else statement I wanted it to echo out Sorry no match if the input field of name is not equal to any name in the database. BUT instead it echo's out Sorry no match once for each name. I understand that I am looping through the array of database name but I only want it to echo Sorry no match once if the name input is not equal to a "firstname" in the database.
EXTRA NOTE:
I have also tried using a foreach loop instead of the while looping with the fetchAll method instead of just fetch but no luck there. Basically gave me the same results.
UPDATE ON THE PROBLEM:
When I load the page the else statement is already taking effect and
echoing out Sorry no match even before I set a name in the input.
and if I type the wrong name it ill echo out Sorry no match twice if
I type the correct name it will echo out the name out of the database
and Sorry no match once.
FIGURED IT OUT:
<?php
$name = $_POST["name"];
require("database.php");
try{
$sql = $conn->prepare("SELECT firstname FROM people WHERE firstname = ?");
$sql->bindParam(1,$name);
$sql->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$theRow = $sql->fetch(PDO::FETCH_ASSOC);
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
echo $theRow['firstname'] . "<br />";
}else{
echo 'no match';
}
?>
Turns out I did not even need a loop do to the WHERE claus only getting the firstname that matched $_POST['name'] so it was just a matter of when to out put that data and that was when the if statement came in. But if I had to output more than one single data I would of probably used a foreach loop like so:
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
echo $row . "<br />";
}
}else{
echo 'no match';
}
If anyone sees any problem with this code or my method please do let me know. Thank you
Firstly, you seem to answer your own question: Why is the else statement running the code twice? Ans: it's not; it's running it once for each iteration of the loop, because you put it in the loop.
Just change your SQL to:
$stmt = $conn->prepare("SELECT firstname FROM people where firstname = ?");
$stmt->execute(array($name));
$result = $stmt->fetchAll();
And it'll either return 1 or 0 rows. So your if statement will look like this:
if($result->num_rows) // True if num_rows > 0; else false
And put your while loop inside your if statement. Keep your else statement to just echo 'Sorry no match';.
This question already has an answer here:
entered form data is not saving in mysql db?
(1 answer)
Closed 9 years ago.
Here is my code:
<?php
include('admin/class.php');
Here is my db connection:
$link = mysqli_connect("localhost", "root", "", "timesheet1234");
Here is the action for save button:
if(isset($_POST['save']))
{
$user=$_SESSION['user'];
$sel =$_POST["selpro"];
$mon =$_POST["mon"];
$tue =$_POST["tue"];
$wed =$_POST["wed"];
$thu =$_POST["thu"];
$fri =$_POST["fri"];
$sat =$_POST["sat"];
$sun =$_POST["sun"];
Checking whether the $user is in db are not:
$sql=mysqli_query($link,"select * from emp
where username='".$_SESSION['user']."'");
$res=mysqli_num_rows($sql);
Here it checks whether to insert are not:
if($res==0)
{
$sql1 = mysqli_query($link,"INSERT INTO emp SET username='$user',
project code='$sel',mon=$mon,tue=$tue,wed=$wed,
thu=$thu,fri=$fri,sat=$sat,sun=$sun");
Here the problem comes:
if($sql1){
echo "<script type='text/javascript'>";
echo "alert('TimeSheet Saved..!')";
echo "</script>";
echo "<script type='text/javascript'>";
echo "window.location='my_tm.php'";
echo "</script>";
}
else
{
echo "<script type='text/javascript'>";
echo "alert('Some Error Occured ! Retry..!')";
echo "</script>";
echo "<script type='text/javascript'>";
echo "window.location='my_tm.php'";
echo "</script>";
}
}
}
?>
Isnt the problem with if($res==0)? Because you check if the session user is in the database and store the number of rows in $res. So I would guess that you want to insert the query when $res==1 (one user) and not when there is no user.
Also normally you have complete control over your session variables. So once you store a user in there, you can trust that its there. Unless ofcourse you made mistakes on the authentication process.
Also in your javascript code you want to use window.location.href='my_tm.php to change the url and not just window.location
Try this as your insert query
$sql1 = mysqli_query("INSERT INTO emp SET username='$user',
`project code`='$sel',mon='$mon',tue='$tue',wed='$wed',
thu='$thu',fri='$fri',sat='$sat',sun='$sun'",$link);
The project code column has space