unable to update City in only insert is performed - php

<?php
session_start();
include_once 'DBconfig.php';
extract($_GET);
$CityName = $_POST['CityName'];
if (isset($CityID))
{
$sql = "UPDATE city SET CityName = '$CityName', Modified = NOW() WHERE city.CityID = $CityID;";
}
else
{
$sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, '$CityName', NOW(), NOW());";
}
$result = mysqli_query($con, $sql);
if ($result)
{
header('location: ListCity.php');
}
else
{
header('location: AddEditCity.php');
}
?>
only insert block will be executed update not working $CityID variable is come from extract function so no naming convention issue can't resolve it please help

You are extracting from $_GET (which is always to be avoided) and then taking $CityName from $_POST. That is inconsistent as the request cannot be both a GET and a POST at the same time. It surely must be a POST request or the insert wouldn't be working at all. And as been commented, you should be using a prepared statement to avoid a SQL injection attack:
<?php
session_start();
include_once 'DBconfig.php';
$CityName = $_REQUEST['CityName'];
if (isset($_REQUEST['CityID']))
{
$CityID = $_REQUEST['CityID'];
$sql = "UPDATE city SET CityName = ?, Modified = NOW() WHERE city.CityID = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "si", $CityName, $CityID);
}
else
{
$sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, ?, NOW(), NOW())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "s", $CityName);
}
$result = mysqli_stmt_execute($stmt);
if ($result)
{
header('location: ListCity.php');
}
else
{
header('location: AddEditCity.php');
}

Related

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

PHP echo all data from database based on input

I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.
I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>

ERROR WHILE INSERTING USING MYSQLI

i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``

Is there anything wrong with mysqli update Query?

I cannot update my existing data in the tabular form of my CRUD web application. Is there anything wrong with the query ? This is my source of reference and I have follow the UPDATE query exactly as in here INSERT, UPDATE and DELETE with mysqli. This is my code.
<?php
//error_reporting(E_ALL^E_NOTICE);
function chgDate($date){
$temp=explode("-",$date);
return $temp[2]."-".$temp[1]."-".$temp[0];
}
$json=array();
$ic = $_POST['IC'];
$Fic = $_POST['fromIC'];
$name = $_POST['formName'];
$tel = $_POST['formTelephone'];
$gender = $_POST['formGender'];
$email = $_POST['formEmail'];
if(isset($_POST['formUni'])){
$uni = $_POST['formUni'];
}
$age = $_POST['formAge'];
$address = $_POST['formAddress'];
$dob = $_POST['formDOB'];
$process= $_POST['process'];
//include ("connect_db.php");
//include_once('connect_db.php');
$db = mysqli_connect("localhost","root","admin","li") or die("Connection Error: " . mysqli_error());
if($process == 'save'){
$SQL="Insert into biodata (IC, Name, Telephone, Gender, Email, University, Age, Address, DOB) values ('$Fic', '$name', '$tel', '$gender', '$email', '$uni', '$age', '$address', '".chgDate ($dob)."')";
$json['newrow']=$Fic;
} else if ($process == 'edit') {
$SQL="UPDATE biodata SET IC='$Fic', Name='$name', Telephone='$tel', Gender='$gender', Email='$email', University='$uni', Age='$age', Address='$address, DOB ='".chgDate ($dob)."' WHERE IC= '$ic'";
} else if ($process == 'delete') {
$SQL = "DELETE FROM biodata WHERE IC='$ic'";
}
$data = mysqli_query($db, $SQL);
if($data){
$json['msg']='success';
}else{
$json['msg']='fail';
}
echo json_encode($json);
?>
It seems you forgot to end the quotes
Address='$address'
Check it
$SQL="UPDATE biodata SET IC='$Fic', Name='$name',
Telephone='$tel', Gender='$gender', Email='$email', University='$uni',
Age='$age', Address='$address', DOB ='".chgDate ($dob)."' WHERE IC= '$ic'";

PHP Prepared Statements - MySQL Check if user exists

I don't know why my code doesn't seem to be working. I want to check if an email exists in the database, and if it doesn't exist proceed with registration. Here's the code:
if (empty($errors)) { //Using Prepared Statements
// Connect to the database:
$dbc = mysqli_connect ('localhost','root', 'pass', 'book_store');
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows == 0) { //Check if email exists
$q = 'INSERT INTO users(first_name, last_name, state, email) VALUES (?, ?, ?, ?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt,'ssss', $fn, $ln,$state, $email);
mysqli_stmt_execute($stmt);
// Closee statement:
mysqli_stmt_close($stmt);
// Close the connection:
mysqli_close($dbc);
} else {
echo '<h1>email exists</h1>';
}
}
else {
echo '<p>The Errors Occurred:<br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '</p><p>Please Try Again.</p>';
}
}
You have given i, which represents variable of type int. Try replacing that with s as given below.
$q = "SELECT user_id FROM users WHERE email=?";
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 's', $email);

Categories