Logic operation failure in php - php

I want to do some logic operation before updating the data in MySQL. However, I think there are some problems in my logic operation. I do not know which line causes the problem. Can anyone help?
<?php
session_start();
if ($_POST['meetingid'] > $_SESSION["id"]){
echo "ERROR: Wrong Meeting_ID. Update failed.<br>";
}
else if(empty($_POST['date'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Date field)<br>";
}
else if(empty($POST['committee'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Committee field)<br>";
}
else if(empty($_POST['session'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Session field)<br>";
}
else{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'admin123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$meetingid = $_POST['meetingid'];
$date = $_POST['date'];
$committee = $_POST['committee'];
$session = $_POST['session'];
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
mysql_select_db('imo resolution v.2');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
else{
echo "Updated data successfully<br>";
}
mysql_close($conn);
}
?>

Here is the code refactored (untested)
Some notes about what has changed:
Changed the initial condition because what would happen if $_POST['meetingid'] was less than $_SESSION['id'] but not equivalent.
Combined the empty() statements together. Your code before would not display correctly if your form had more than 1 empty field.
mysql_ functions are deprecated. Don't use them! Use mysqli_ instead.
Added some basic santisation through mysqli_real_escape_string() function
Removed mysql_select_db() as you can set the database through mysqli_connect()
Updated the code to check whether the INSERT statement was successful
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbdb = 'imo_reslution_v.2';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbdb);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$meetingid = mysqli_real_escape_string($conn, $_POST['meetingid']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$committee = mysqli_real_escape_string($conn, $_POST['committee']);
$session = mysqli_real_escape_string($conn, $_POST['session']);
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
$retval = mysqli_query( $sql, $conn );
if( mysqli_infected_rows() == 0 ) {
die('Could not update data: ' . mysqli_error());
}else {
echo "Updated data successfully<br>";
}
mysqli_close($conn);
}
?>

Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
As per mulqin suggestion (untested)
try to use prepared statement to avoid sql injections
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = "admin123"; //password
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,`imo_resolution_v.2`) or die("Opps some thing went wrong");
$stmt = $conn->prepare("UPDATE `meeting` SET `Date`=? ,`Committee`=? ,`Session`=? WHERE `Meeting_ID`=? ");
$stmt->bind_param('ssii',$date,$committee,$session,$meetingid);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
$stmt->close();
$conn->close();
if($row_count>0)
{
echo "Updated data successfully<br>";
}
else
{
echo "Not Updated";
}
}
?>

Related

Cant perform an SQL update when using php varibles

I just noticed that i can not perform SQL updates when i am using PHP varibles from the link
My code (I don't noticed any errors, and no error output)
<?php
if ($_POST && isset($_POST['hdduid'], $_POST['status'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'L24wmc1nJBVP90q9yY';
$dbname = 'watt';
try {
// Try to connect
$dbh = new PDO(
'mysql:host='.$dbhost.';dbname='.$dbname,
$dbuser,
$dbpass
);
// Data
$hdduid = $_POST['hdduid'];
$status = $_POST['status'];
// query
$sql = "UPDATE users SET paid=':status' WHERE hdduid=':hdduid'";
$q = $dbh->prepare($sql);
$q->execute(array(
':message' => $message,
':email' => $email
));
// Null connection
$dbh = null;
} catch (PDOException $e) { // if exception
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
I edited the code, it still wont working
You need to use
mysqli_real_escape_string
Not
mysql_real_escape_string
You can not mix mysql with MySQLi
Here is another solution using prepared statements.
$servername = "localhost";
$username = "root";
$password = "L24wmc1nJBVP90q9yY";
$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$paid = $_GET["status"];
$hdduid = $_GET["hdduid"];
//Prepared statements
$statement = $connection->prepare("UPDATE users SET paid = ? WHERE hdduid = ?");
$statement->bind_param("ss", $paid, $hdduid);
if(!$statement->execute()) {
echo "Error updating record: " . $statement->error;
} else {
echo "Record updated successfully";
}
$statement->close();
$connection->close();
Here is a solution. It uses mysqli_real_escape_string instead of mysql_real_escape_string. I also changed the name of $status to $paid for better readability. Good luck!
$servername = "localhost";
$username = "root";
$password = ""; //$password = "L24wmc1nJBVP90q9yY";
$dbname = "test"; //$dbname = "ft";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$hdduid = $_GET["hdduid"];
$paid = $_GET["status"];
$sql = "UPDATE users SET paid='$paid' WHERE hdduid='$hdduid'";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();

Getting error Record updated successfully Fatal error: Uncaught Error: Call to a member function fetch_assoc() on array

<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.

Why I am getting a lines under the table in phpmyadmin(localhost)

I am trying to send a data from android studio, but I am getting lines under the table instead of assigning data.
Dont know where I am gone wrong.Plz help me.Thanks in advance.
This is my PHP code
add_employee
<?php
include('connection.php');
if (isset($_POST["name"])){
$emp_name = $_POST["name"];
echo $emp_name;
echo "is your name";
}
else{
$emp_name = NULL;
echo "POST filename is not assigned";
}
$success = 0;
$status = "Active";
$sqli = "INSERT INTO `employee` (`emp_name`) VALUES ('$emp_name')";
if(mysqli_query($conn,$sqli)){
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysqli_close($conn);
?>
Connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($conn,'student');
?>
You have so many errors in your code. no db name, no proper query definition. you can use this simple code:
Connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "slim";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Inserting employee code:
<?php
if (isset($_POST["name"])){
$emp_name=$_POST["name"];
echo $emp_name;
echo "is your name";
}
else{
$emp_name = null;
echo "POST filename is not assigned";
}
$success=0;
$status="Active";
$sql = "INSERT INTO employee (name)
VALUES ('$emp_name')";
if ($conn->query($sql) === TRUE) {
$success=1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
It's working and easy to understand for you.

Data already Inserted I want to update the data

I am getting issue in update code.I am able to inserted data in database.I am passing null values in table. I want to update that null values.I am getting the sccessfully message but data is not updating. Please help me....
//Insert code
<?php
// Start the session
session_start();
?>
<?php
// Start the session
session_start();
?>
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
}
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=isset($_POST['product']);
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Id='(select count(*) from contactus)' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>
I see no point in doing an Insert and then doing an Update. You already have all the data, so just Insert it all at once.
EDIT AFTER COMMENTS
First Handler:
<?php
start_session();
if(isset($_POST['product'])){
$product=$_POST['product'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($result = $mysqli->query("INSERT INTO contactus (Id,Product) VALUES ('null','$product')")) {
// Grab new ID when INSERT is successfull, add it to Session
$_SESSION['contact_id'] = $mysqli->insert_id;
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
$mysqli->close();
exit();
}
$mysqli->close();
}
header('Location: /newstore/contact.html');
?>
Second Handler:
<?php
start_session();
// form data
$name=isset($_POST['name'])?$_POST['name']:"";
$email=isset($_POST['email'])?$_POST['email']:"";
$mobile=$_POST['mobile'];
if ((strlen($name) < 3) || (strlen($email) < 3) || (strlen($mobile) < 3)){
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
exit();
}
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($stmt = $mysqli->prepare("UPDATE contactus SET `Name`=?, `Email`=?, `Mobile`=?) WHERE `ID`=?")){
/* bind parameters for markers */
$stmt->bind_param("sssi", $name, $email, $mobile, $_SESSION['contact_id']);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
$stmt->close();
}
$mysqli->close();
?>

Could not enter data: Unknown column 'emp_salary' in 'field list'

Here is the code that causes the error I pasted in the title. I am pretty sure the error comes from the query but cannot figure it out.
The last thing I have tried is the "real escape" function you can see here and that I found as a response in some other questions of the same type; still the same error. I am starting with coding and might just be stupid... anyways, thanks for your help!
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'boom';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$emp_name = addslashes ($_POST['emp_name']);
$emp_address = addslashes ($_POST['emp_address']);
$emp_salary = addslashes ($_POST['emp_salary']);
}
else
{
$emp_name = $_POST['emp_name'];
$emp_address = $_POST['emp_address'];
$emp_salary = $_POST['emp_salary'];
}
$sql = "INSERT INTO employee (emp_name,emp_address,emp_salary)
VALUES('".mysql_real_escape_string($emp_name)."','".mysql_real_escape_string($emp_address)." ','".mysql_real_escape_string($emp_salary)." ')";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
create the column named emp_salary in respective table.
You must not use mysql_ function family as you are more prone to SQL attacks with these.
Either use mysqli or better to use PDO

Categories