I am trying to update the record of Employee.MY query shows the message "Employee record updated Successfully" but it is not updating in table My code goes like this
{
$eid=intval($_GET['uin']);
$uin=$_POST['uin'];
$fname=$_POST['firstName'];
$lname=$_POST['lastName'];
$email=$_POST['email'];
$department=$_POST['department'];
$recoffr=$_POST['recoffr'];
$mobileno=$_POST['mobileno'];
$sql="
update tblemployees
set FirstName = :fname
, LastName = :lname
, email = :email
, department = :department
, recoffr = :recoffr
, Phonenumber = :mobileno
where uin = :eid
";
$query = $dbh->prepare($sql);
$query->bindParam(':uin',$uin,PDO::PARAM_STR);
$query->bindParam(':fname',$fname,PDO::PARAM_STR);
$query->bindParam(':lname',$lname,PDO::PARAM_STR);
$query->bindParam(':email',$email,PDO::PARAM_STR);
$query->bindParam(':department',$department,PDO::PARAM_STR);
$query->bindParam(':recoffr',$recoffr,PDO::PARAM_STR);
$query->bindParam(':mobileno',$mobileno,PDO::PARAM_STR);
$query->execute();
$msg="Employee record updated Successfully";
}
My table structure is Table structure
You have assigned Uin to wrong Id
$query->bindParam(':eid',$uin,PDO::PARAM_STR);
not
$query->bindParam(':uin',$uin,PDO::PARAM_STR);
you can try this:
if (isset($_GET['uin'])) {
$ID = $_GET['uin'];
} else {
$ID = "";
}
$tblemployees_data = array();
$sql_query = "SELECT firstName, lastName, email, department, recoffr, mobileno
FROM tblemployees
WHERE uin = ?";
if ($query_category->prepare($sql_query)) {
// Bind your variables to replace the ?s
$query_category->bind_param('s', $ID);
// Execute query
$query_category->execute();
// store result
$query_category->store_result();
$query_category->bind_result($previous_category_image);
$query_category->fetch();
$query_category->close();
}
Related
I am working on a project that takes students attendance in class and I want to update the database data through PHP whilst running a SQL function of UPDATE, but I want to be able to update it base on the id of the data.
This is the code that I am working with at the moment.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
} elseif(isset($_POST['time_out'])) {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = ? ";
$d = $conn->prepare($query);
$d->execute();
} else {
$status = "Can't time in!";
}
Use $conn->lastInsertId() to get the ID that was assigned when they clocked in. Save that in a session variable and use it when they clock out.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
$_SESSION['clock_id'] = $conn->lastInsertId();
} elseif(isset($_POST['time_out'])) {
if (!isset($_SESSION['clock_id'])) {
$status = "You need to clock in first!";
} else {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $_SESSION['clock_id']]);
}
} else {
$status = "Can't time in!";
}
You must remember to prepare the query and bind the parameters onto it.
Use the $id variable to prepare the query with the appropriate ID.
Make sure you authenticate the session before passing the ID to the query, otherwise an attacker can manipulate this data to pull anyone's data they wish.
// Its helpful to create elements within the code to bind onto. :id is ours.
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
// Run the query & bind id to :id
$d->execute(['id' => $id]);
You try update
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $id ]);
I have a table named city where the are city_id and city_name columns there. What I want is that I want to query the value of city_id from the city table into another table named spinner which also contain city_id column there.
Both city_id have same int data type.
Here is my php code sample
<?php
$response = array();
include 'DBConnect.php';
//Get the input request parameters
// $inputJSON = file_get_contents('php://input');
// $input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
$city_name = $_POST['city_name'];
// $city_id = $_POST['city_id'];
// $city_query = "SELECT city.city_id FROM city INNER JOIN spinner ON city.city_id = spinner.city_id";
// $sql = "SELECT city_id FROM city WHERE $city_name ";
// $stmt = $con->query("SELECT city_id FROM city WHERE $city_name");
// $city_id = $stmt;
// $insertQuery = "INSERT INTO spinner(city_id) VALUES (?)";
$insertQuery = "INSERT INTO spinner(city_id) SELECT city_id FROM city WHERE $city_name";
if($stmt = $con->prepare($insertQuery)){
// $stmt->bind_param('s',$city_id);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "city data sent";
$stmt->close();
}
else{
$reponse["message"] = "cannot send data";
}
echo json_encode($response);
?>
The subquery part always be in (). And check the WHERE condition according to your need:
INSERT INTO spinner(city_id) VALUES((SELECT city_id FROM city WHERE city_name = "$city_name"))
You're forgetting to set your values. Your syntax should be something like this
INSERT INTO spinner(city_id) VALUES((SELECT city_id FROM city WHERE city_name = '$city_name'))
Just a quick comment, I would personally separate my query. I wouldn't nest them
i would like to know why i am not able to insert new data to my Database.
in vardump i get good result but nothing is added to my database
Database : c_id = AutoInc. | a_id | u_id | c_head | c_content | c_date
=TIMESTAMP
if (isset($_POST['c_submit'])) {
$sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
$vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
if (mysqli_num_rows($vysledokHladania) == 1) {
while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
$sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], $_POST[c_hlavicka], $_POST[c_obsah], 'NOW()')";
mysqli_query($connect_to_db, $sql_vloz_komentar);
}
}
}
You can use date('Y-m-d h:i:s') to store current date time in our DB by PHP code and in your query you just missed to put '' in array index.
Try this one
if (isset($_POST['c_submit'])) {
$date=date('Y-m-d h:i:s');
$sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '".$_SESSION['username']."'";
$vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
if (mysqli_num_rows($vysledokHladania) == 1) {
while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
$sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES
(".$_GET['a_id'].",".$db_data_prihlaseneho_uzivatela['u_id']." ,".$_POST['c_hlavicka']." ,".$_POST['c_obsah']." ,$date)";
mysqli_query($connect_to_db, $sql_vloz_komentar);
}
}
}
I thing it will help you.
do you escape the varchar character ?
Other posible error is the date format in database.
Postecho $sql_vloz_komentar for view the insert statement and the structure of table
if (isset($_POST['c_submit'])) {
$sql_najdi_prihlaseneho_uzivatela = "SELECT * FROM users where u_name = '$_SESSION[username]'";
$vysledokHladania = mysqli_query($connect_to_db, $sql_najdi_prihlaseneho_uzivatela);
if (mysqli_num_rows($vysledokHladania) == 1) {
while ($db_data_prihlaseneho_uzivatela = mysqli_fetch_assoc($vysledokHladania)) {
$sql_vloz_komentar = "INSERT INTO comments (a_id, u_id, c_head, c_content, c_date) VALUES ($_GET[a_id], $db_data_prihlaseneho_uzivatela[u_id], '$_POST[c_hlavicka]', '$_POST[c_obsah]', 'NOW()')";
mysqli_query($connect_to_db, $sql_vloz_komentar);
}
}
}
I'm trying to edit data(stored in DB). This is display.php. First it displays data from DB (if no data then blank fields). Then edit button to edit DB.
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
And in edit.php
i simply update the DB. But what if i want to change only 1 field.(problem is all fields gets updated).Here's edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
this query means:
update table user
for each row in this table where u_id = [some value]
set fields C and S and T to some other distinct values
so, your query updates 3 fields at one time, and it is ok, as it what it should do
if you want to change this logic, to update only some fields you need to change query and arguments, for example if you want to change only c use:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
for c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
if you don't know exactly how many arguments will be, you need dynamic query building, like:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
That means that WHERE clause of the request doesn't work. Check if you passing a quotation marks " in you variable $t so you close $sql before WHERE clause
is there any way how in this situation insert and update DB with single queries?
$message = 'Hello to all group members';
$userdata = mysql_query("SELECT memberid, membernick FROM members WHERE groupid='$cid'") or die('Error');
while(list($memberid, $membernick) = mysql_fetch_row($userdata)) {
$result1 = mysql_query("INSERT INTO messages VALUES (NULL,'$membernick', '$memberid', '$message')") or die('Error');
$result2 = mysql_query("UPDATE users SET new_messages=new_messages+1, total_messages=total_messages+1 WHERE id='$memberid'") or die('Error');
}
The update and insert can be one-ified with mysql >= 5.1. Try
$message = 'Hello to all group members';
$userdata = mysql_query("SELECT memberid, membernick FROM members WHERE groupid='$cid'") or die('Error');
$memberids = array();
$values = array();
while(list($memberid, $membernick) = mysql_fetch_row($userdata)) {
array_push($values, "(NULL,'$membernick', '$memberid', '$message')");
array_push($memberids, "'$memberid'");
}
// ==> replace colX with the names of your columns
// check http://dev.mysql.com/doc/refman/5.1/en/insert.html for further information
$result1 = mysql_query("INSERT INTO messages (col1,col2,col3,col4) VALUES ".implode(",", $values)) or die('Error');
$result2 = mysql_query("UPDATE users SET new_messages=new_messages+1, total_messages=total_messages+1 WHERE id IN (".implode(",", $memberids).")") or die('Error');
I Hope this will help
Jerome Wagner
Nope, MySQL doesn't have a support for updating or inserting multiple rows in multiple tables with a single query.