Update data from comboBox using PHP - php

I need your help..
In my web site, I let the employee to chose the department name that he wants from comboBox using this code
$dept_id = $_SESSION['dept_id'];
$from= "SELECT d.dept_id, d.name FROM department d LEFT JOIN employee e ON d.dept_id = e.dept_id WHERE emp_id = '$emp_id' ";
$result_form = mysql_query($from);
//$row1 = mysql_fetch_array($result_form); // get 1st result row
$dept_from = mysql_fetch_assoc($result_form);
$dept_name = $dept_from['name'];
//$row=mysql_fetch_array($result_form);
//echo $row1['name'];
$date1=date("Y/m/d");
$dept_id = $_SESSION['dept_id'];
$query = "INSERT INTO request (`date`, `description`, `from`, `emp_id`, `to`)
VALUES
('$date1','$_POST[description]','$dept_name','$emp_id','$_POST[to]')";
it works correctly
Then the administrator choose the request by employee ID from comboBox when he press the accept button the data should updated
and this is its code
if(array_key_exists('accept', $_POST)) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("employee_transfare", $conn);
$emp_id=$_POST['emp_id'];
$dept_id = $_SESSION['dept_id'];
$query="UPDATE employee SET dept_id='$dept_id' WHERE emp_id= $emp_id ";
$n=mysql_query($query, $conn);
if($n==0)
echo "<h2>details already updated </h2>";
else
echo "<h2>details successfully updated</h2>";
mysql_close($conn);
}
else {
It always gives details already updated ...
How I can do it?

That comparison with 0 seems a bit imprecise. The following is from the documentation on mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
Instead of if ($n==0), perhaps try if ($n===FALSE) or alternately if (! $n).

Related

php & mysql please select an other date- message is not appearing

I have two issues and both are linked. First, "already booked - please select another date" is not appearing, if two clients select the same product (pg_no) and date (Date). These fields are UNIQUE CONSTRAINT.
Second, when data is inserted or submitted localhost shows complete address
http://localhost/lstcomp/index.php?note=submitted. But when it fails the localhost shows only : http://localhost/lstcomp/
<?php
//connecting string
include("dbconnect.php");
//assigning
$name = $_REQUEST['Name'];
$tele = $_REQUEST['Tele'];
$city = $_REQUEST['City'];
// UNIQUE CONSTRAINT
$pg_no = $_REQUEST['pg_no']; //product
$date = $_REQUEST['Date']; //date
//checking if pg_no and Date are same
$check = mysqli_query($db_connect, "SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
mysqli_close($db_connect);
// messaging
if ($query) {
header("location:index.php?note=failed");
} else {
header("location:index.php?note=success");
}
?>
There are a few problems:
The file fails to parse because of the dangling else; it's not paired with an if-statement.
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
It looks like you're intending to use the result from your SELECT statement ($check), however...
The SELECT statement is invalid; WHERE clauses are separated with AND or OR, not commas.
When inserting the row into the database table, you're dying on mysql_error when you've been using the mysqli extension.
You're vulnerable to SQL injection attacks; if pg_no happened to be '; DELETE FROM users; --, as an example, your user table would be deleted. You're already using the mysqli extension, so use parameter binding and prepared statements. Reference

How to update multiple fields in Database

I have a databse photos in which the record of members are stored, it has name, au_id , position , contact & email columns. There is secured panel where admin can change the details of the body members of the group. Complete form is shown again here with the values stored in database so if admin want to change any value he/she can do here and submit that form to update record. On successfull submission
$name=$_POST['name'];
$au_id=$_POST['au_id'];
$position=$_POST['position'];
$contact=$_POST['contact'];
$email=$_POST['email'];
I am having trouble to update records of particular member. I have primary key id in my database. I am using:
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
$result=mysql_query($save);
and putted a check so that i can know that if query is successfully run or not,
if (mysql_num_rows($result))
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
it is giving successfully updated message but when i again go to check the records nothing is changed. how can i figure out this problem
$save="UPDATE photos SET name = '".$name."', au_id = '".$au_id."', position = '".$position."', cell = '".$contact."', email = '".$email."' WHERE id = '6' ";
$result=mysql_query($save);
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
if ($result=mysql_query($save))
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
mysql_num_rows should not be used for the SQL querys which does not return result set, like UPDATE, DELETE and so on.
mysql_query it self seems to work in some situations if mysql connection is properly done by mysql_connect and db is properly selected using mysql_select_db. So you should check whether the SELECT query works there.
However, if one of field contains "'", for example, your SQL query is collapsed. This is not just a problem which leads to error, but a vulnerability which allows "SQL injection". You should use placeholder. If placeholder can't be used for some reason, you must use mysql_real_escape_string to escape your fields.
As you are mention in your question columns are :-
name, au_id , position , contact & email
two things I have catch in your code:-
1) You are mention contact column and your updating with cell.
2) You have not declare $contact variable.
Please run query with correct column name and if id is not string then no need to use id = '6' you can use id = 6
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.check this link
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
So you get true or false on executing the query and obviously mysql_num_rows(true) makes no sense.
try this:
use mysql_affected_rows()
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
$result=mysql_query($save);
$cnt=mysql_affected_rows();
if($cnt>0)
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
mysql_ is deprecated function

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

INSERT INTO table1 values FROM table2 WHERE

I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.

Update/Insert into mysql query

I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.

Categories