PHP Update Confusion - php

I am updating MySQL row using the following code. could any one tell me how i can error check the update query and only print Success if the update query was successful without any error? and print failed if update query was not successful!
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
// $get_contact = "SELECT * FROM `contacts` where contacts_id = '$contact_id'";
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '$contact_id'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='$fname',`last_name`='$lname',`cellphone_number`='$cphone',`city`='$city' WHERE contacts_id = ". $contact_id;
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
My question is this: I'm doing my best to find whats the error and i couldn't what it is. It is for my elective project.

first of all please learn how to use procedure based query to be safe from SQL injection( I am not here to give tutorials on procedure and SQL injection, it is just warning against malicious code) and now your code solution. There was a problem in the way you were concatenating a variable with a string in your query. I have fixed that part for you.
if you still get any error then share what error you are getting and what is the error message.
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '".$contact_id."'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='".$fname."',`last_name`='".$lname."',`cellphone_number`='".$cphone."',`city`='".$city."' WHERE contacts_id = '".$contact_id."'";
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>

use this function:
function alertBox($alert_msg, $redirect_link)
{
$alert = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$alert .= '<script type="text/javascript">alert("'.$alert_msg.'");';
if(!empty($redirect_link)):
$alert .='window.location="'.$redirect_link.'";';
endif;
$alert .='</script>;';
return $alert;
}
// and for calling..
if((mysqli_query($con,$sql))
{
echo alertBox("sucessfull","example.php");
}

Related

How do I echo message at the top of the form, after performing insertion, update and delete on same page, while using header("location:$url");

How do I echo message at the top of the form, after performing insertion, update and delete on same page, while using header("location:$url");
if($_SERVER["REQUEST_METHOD"] == "GET"){
if(isset($_GET['id1'])){
$Id1 = base64_decode($_GET['id1']);
$qry = "SELECT Name,Description,Role FROM cms WHERE id='$Id1'";
$res = mysqli_query($conn, $qry);
$res1 = mysqli_fetch_assoc($res);
$uname = $res1['Name'];
$address = $res1['Description'];
$role1 = $res1['Role'];
}
}
if(isset($_POST['update']))
{
if(isset($_GET['id1']))
{
$id1=base64_decode($_GET['id1']);
$uname = $_POST['uname'];
$address = $_POST['address'];
$role = $_POST['role'];
$qry2 = "UPDATE cms SET Name ='$uname', Description = '$address',Role='$role' WHERE
id='$id1'";
$res2 = mysqli_query($conn,$qry2);
if(mysqli_error($conn))
{
echo "error";
} else {
$_SESSION['success'] = "Record Updated Successfully!";
header("location:admin.php");
}
}
}
?>
I tried running the above code in HTML snippet to display the echo message on my webpage but it does not echo the message with header tag

How can I update an exisiting image with MYSQL

I'm trying to update an existing image in my database using mysql query.
This is my edit.php where i edit user info
<?php
require_once "config.php";
if(isset($_GET['edit']))
{
$id = $_GET['edit'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
}
if(isset($_GET['id']))
{
$newText = $_GET['voornaam'];
$newText2 = $_GET['tussenvoegsel'];
$newText3 = $_GET['achternaam'];
$newText4 = $_GET['stemsoort'];
$newText5 = $_GET['adres'];
$newText6 = $_GET['postcode'];
$newText7 = $_GET['plaats'];
$newText8 = $_GET['telefoon'];
$newText9 = $_GET['mobiel'];
$newText10 = $_GET['email'];
$newText11 = $_GET['status'];
$newText12 = $_GET['lid_sinds'];
$newText13 = $_GET['lid_tot'];
$id = $_GET['id'];
$res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
$row = mysqli_fetch_array($res);
$sql = "UPDATE user_data SET voornaam='$newText', tussenvoegsel='$newText2', achternaam='$newText3', stemsoort='$newText4', adres='$newText5', postcode='$newText6', plaats='$newText7', telefoon='$newText8', mobiel='$newText9', email='$newText10', status='$newText11',lid_sinds='$newText12',lid_tot='$newText13' WHERE id=$id";
$res = mysqli_query($link,$sql)
or die("Could not update".mysqli_error($link));
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
And this is how I upload images to a folder and then into mysql database
<?php
$msg = "";
$css_class = "";
$conn = mysqli_connect('localhost','root','','test');
if (isset($_POST['save-user'])) {
echo "<pre>", print_r($_FILES['profileImage']['name']),"</pre>";
$bio = $_POST['bio'];
$profileImageName = time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target)) {
$sql = "INSERT INTO users (profile_image, bio) VALUES ('$profileImageName','$bio')";
if (mysqli_query($conn,$sql)) {
$msg = "image uploaded";
$css_class = "alert alert-success";
}else {
$msg = "Database Error: Failed to save user";
$css_class = "alert alert-danger";
}
} else {
$msg = "Failed to upload image";
$css_class = "alert alert-danger";
}
}
?>
How can I combine the two and let a user edit his uploaded profile image? Thanks for helping out

Why does my code delete the first row from database

i need your help. I have my delete all records button, when i delete all records it works fine until when i try to add records after the delete all, the first record will be deleted when i try to add the second record. i think the problem is because i never close my query after the delete all records.. i dont the exact syntax that can be used in my codes. please help me guys.
here is my code for delete all:
<?php
include_once 'connection.php';
$fname = $lname = $username = $phone = $email = $cemail = "";
$act="";
$txtid = 0;
if(isset($_GET['act'])){
$act=$_GET['act'];
if($act=='delete'){
$id=$_GET['id'];
$sql="delete from tbl_admin where id = $id";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
if($result){
}
}
if($act=='deleteall'){
$sql="delete from tbl_admin";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
}
if($act=='edit'){
$id=$_GET['id'];
$sql="select * from tbl_admin where id = $id";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
while($row = mysqli_fetch_array($result)){
$txtid = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$username = $row['username'];
$phone = $row['mobileNo'];
$email = $row['email'];
}
}
if(isset($_POST['add'])){
// fname validate
if(empty($_POST["fname"])){
echo '<script> alert("first name is empty!"); </script>';
}else{
$fname = test_input($_POST["fname"]);
// lname validate
if(empty($_POST["lname"])){
echo '<script> alert("last name is empty!"); </script>';
}else{
$lname = test_input($_POST["lname"]);
//username
if(empty($_POST["username"])){
echo '<script> alert("username is empty!"); </script>';
}else{
$username = test_input($_POST["username"]);
//phone
if(empty($_POST["phone"])){
echo '<script> alert("mobile number is empty!!"); </script>';
}else{
$phone = test_input($_POST["phone"]);
//email
if(empty($_POST["email"])){
echo '<script> alert("email is empty!"); </script>';
}else{
$email = test_input($_POST["email"]);
//cemail
if(empty($_POST["cemail"])){
echo '<script> alert("confirm email is empty!"); </script>';
}else{
$cemail = test_input($_POST["cemail"]);
if($email != $cemail){
echo '<script> alert("Confirm Email!"); </script>';
}else{
$sql= "insert into tbl_admin(fname,lname,username,password,mobileNo,email,add_date) values('$fname','$lname','$username','123abc','$phone','$email',NOW())";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
if($result){
echo '<script> alert("Successfully add admin user."); </script>';
$fname = $lname = $username = $phone = $email = $cemail = "";
}
}
}
}
}
}
}
}
}
if(isset($_POST['update'])){
if(empty($txtid)){
echo '<script>
alert("Select record to Update!");
</script>';
}else{
echo '<script>
alert("you can update record..");
</script>';
$fname = $lname = $username = $phone = $email = $cemail = "";
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Because ALL your code exists inside this if statement
if(isset($_GET['act'])){
Then we have to assume that $_GET['act'] is always set to something
Because $_GET['act'] is always set to something then the DELETE code is getting run ALWAYS. Either its delete or deleteall
The code that rebuilds your web page is still missing, but basically you need to organise your code more logically, and also make sure that $_GET['act'] is only set when you actually want to do a delete, which would probably mean changing the HTML so it is not being left set.
I guess the methods are the same as it was in mysql (without i)
http://php.net/manual/en/mysqli-result.free.php
with non-object-oriented way it would be
mysqli_free_result($result);

how to solve update query error

My error is
Error while updating: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '1' at line 1
Kindly note down no error in speeling no error in post I checked every bit.. updation query is causing that error. I tried many times but didn't resolved. Thanks in advance.
<?php
include('db.php');
session_start();
if(isset($_POST['update']))
{
$fname = mysql_real_escape_string($_POST['fname'], $con1);
$lname = mysql_real_escape_string($_POST['lname'], $con1);
$phone = mysql_real_escape_string($_POST['phone'], $con1);
$zip = mysql_real_escape_string($_POST['zip'], $con1);
$city = mysql_real_escape_string($_POST['city'], $con1);
$country = mysql_real_escape_string($_POST['country'], $con1);
$userId = $_SESSION['userID'];
$strSQL = mysql_query("SELECT * FROM sarah_cloudRecord.user_info WHERE userId = '$userId'" , $con1);
//$Results = mysql_fetch_array($strSQL);
$numrows = mysql_num_rows($strSQL);
if($numrows != 0)
{
while ($row = mysql_fetch_assoc($strSQL))
{
$dblname = $row['lastName'];
$dbfname = $row['firstName'];
$dbphone = $row['phone'];
$dbzip = $row['zipCode'];
$dbcity = $row['city'];
$dbcountry = $row['country'];
if ($fname != $dbfname || $fname == $dbfname)
{
$newfName = $fname;
}
if ($lname != $dblname || $lname == $dblname)
{
$newlName = $lname;
}
if ($phone != $dbphone || $phone == $dbphone)
{
$newPhone = $phone;
}
if ($zip != $dbzip || $zip == $dbzip)
{
$newZip = $zip;
}
if ($city != $dbcity || $city == $dbcity)
{
$newCity = $city;
}
if ($country != $dbcountry || $country == $dbcountry)
{
$newCountry = $country;
}
}
$updateSQL = mysql_query("UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'", $con1);
if (mysql_query($updateSQL, $con1))
{
echo "Update Successfully!";
}
else {
echo "Error while updating: " . mysql_error($con1);
}
}
else {
echo "no records found";
}
}
else
{
?>
<script type="text/javascript">
window.location = "http://dev.metawarez.com/cloud/login.php";
</script>
<?php
}
?>
Using mysql_query two time. You change your update query to
$updateSQL = "UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'";
if (mysql_query($updateSQL, $con1))
Note:- mysql is deprecated instead use mysqli or pdo
You are querying the reply from the UPDATE, thats where the 1 comes from.
http://php.net/manual/de/function.mysql-query.php
$updateSQL = mysql_query("UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'", $con1);
if ($updateSQL !== false)
{
echo "Update Successfully!";
} else {
echo "Error while updating: " . mysql_error($con1);
}

PHP update table using MySQL

I have student table in my DB , and I need to create extra form in student page so he can update the details. However im getting this error ( Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\WebInterfaceLogIn\studentEdit.php on line 81)
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
include ('includes/connection.php');
// Create connection
if (isset($_POST["submit"]))
{ //Determine if a variable is set and is not NULL.
if (!empty($_POST['ID']) && !empty($_POST['user']) && !empty($_POST['surr']) && !empty($_POST['course']) && !empty($_POST['mail']) && !empty($_POST['pass']))
{ //Determine if user enters both user name and password.
$ID = $_POST['ID']; // enters user ID in database
$user = $_POST['user']; // enters user name in database
$surr = $_POST['surr']; // enters user surname in database
$course = $_POST['course']; // enters user course in database
$pass = $_POST['pass']; // enters password in database
$mail = $_POST['mail'];
// $query = mysqli_query($con,"SELECT * FROM students WHERE Student_ID='".$ID."'"); // change to update
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");
$numrows = mysqli_num_rows($query);
if ($numrows == 0)
{
$sql = "INSERT INTO students(Student_ID,Name,Surname,Course,email,password) VALUES('$ID', '$user','$surr','$course','$mail','$pass')"; // insert user name and password to database
$result = mysqli_query($con, $sql);
// Checks does user enters the details
if ($result)
{
echo '<script language="javascript">;
alert("Account Successfully Updated");
document.location.href="index.php";
</script>';
}
else
{
echo mysqli_error($con);
}
}
}
else
{
echo '<script language="javascript">
alert("All fields required")
</script>';
}
}
Can anyone can help to solve this problem?
You need pass connection object to function mysqli_query, something like this:
mysqli_query($con,"UPDATE students SET `course` = " .$_POST['course']. ", `email` = " .$_POST['mail']. " Student_ID='".$ID."'");
See more details on:
http://www.w3schools.com/php/func_mysqli_query.asp
The error is explicit enough.
add $con as a first parameter to your mysqli_query function on this line:
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");

Categories