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
Related
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");
}
i'm very new in PHP programming. I have a code for update database value with 2 condition. Here is my code.
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("");
$id = $_REQUEST["id"];
$serial_number = $_REQUEST["serial_number"];
$email = $_REQUEST["email"];
$nama = $_REQUEST["nama"];
$password = $_REQUEST["password"];
/*** Check Email Exists ***/
$strSQL = "SELECT * FROM iot WHERE email = '".$email."' AND id != '".$id."'";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Email Exists!";
echo json_encode($arr);
exit();
}
/*** Update ***/
$strSQL = " UPDATE iot SET
email = '".$email."'
,nama = '".$nama."'
,password = '".$password."'
WHERE id = '".$id."' AND serial_number = '".$serial_number."'
";
$objQuery = mysqli_query($objConnect,$strSQL);
if(!$objQuery)
{
$arr['Report'] = "Cannot save data!";
}
else
{
$arr['Report'] = "Saved";
}
mysql_close($objConnect);
echo json_encode($arr);
?>
What i want is if one of two condition not meet, then it will show a report " Cannot Save Data".
Sorry for my bad english.
Cheers.
I have been trying to retrieve a row from mysql database with no success. the row that i have been retrieving is only one. here is my code below:
<?php
$email = $_POST["email"];
$usrname = $_POST["username"];
$pass = $_POST["password"];
$code = $_POST["code"];
$status = $_POST["status"];
$userinfo = $_POST["user_info_id"];
$firstname = $_POST["fname"];
$middlename = $_POST["mname"];
$lastname = $_POST["lname"];
$img = $_POST["image"];
require "init.php";
$query = "select * from user where email like '".$email."';";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result)>0)
{
$response = array();
$code = "reg_false";
$message = "User already exist";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$query = "insert into user (email,username,password,code,status,user_info_id) values('".$email."','".$usrname."','".$pass."','".$code."','".$status."','".$userinfo."');";
//$query2 = "insert into userinfo (fname,mname,lname) values('".$firstname."','".$middlename."','".$lastname."');";
$result = mysqli_query($con,$query);
if(!$result)
{
$response = array();
$code = "reg_false";
$message = "Error try again";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$query = "select user_info_id from user group by user_info_id DESC limit 1";
$result = mysqli_query($con, $query);
if ($mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["user_info_id"]. " - Name: " . $row["fname"]. " " . $row["lname"]. $row["mname"] . "<br>"; }
}
$query1 = "insert into userinfo (user_info_id,fname,mname,lname) values('".$result."','".$firstname."','".$middlename."','".$lastname."','".$img."');";
$result = mysqli_query($con,$query1);
$response = array();
$code = "reg_false";
$message = "Success";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
}
mysqli_close($con);
?>
The error I was getting was:
Notice: Undefined variable: mysqli_num_rows in C:\xampp\htdocs\loginapp\register.php on line 46
Fatal error: Uncaught Error: Function name must be a string in C:\xampp\htdocs\loginapp\register.php:46 Stack trace: #0 {main} thrown in C:\xampp\htdocs\loginapp\register.php on line 46
I am fairly new to php and mysql.
Please use this query to get num rows.
$query = "select * from user where email like '".$email."';";
$result = mysqli_query($con,$query);
$row_count = mysqli_num_rows($result);
Then use your if conditions like this
if ($row_count>0)
{
$response = array();
$code = "reg_false";
$message = "User already exist";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
.......
I am new in stackoverflow and in PHP too, so I want to describe my problem first. Sorry if I have bad grammar, I am not native though.
I make a form that let user post (to database) with or without an image, this the code
$link = mysqli_connect('localhost', 'root', '12345!##', 'pklapps') or die("Couldnt connect to the server");
//public info dari admin
if (isset($_POST["title"]) && isset($_POST["content"]) && isset($_POST["category"])) {
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if (!isset($_FILES['userfile'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
} else {
header('Location: post.php?error');
}
} else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if ($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
} else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
}
and the form goes normal when i attach the image or file but it goes to header('Location: post.php?errimg'); when i not attach the image. Please help me with this, thank you.
Replace your if condition from !isset($_FILES['userfile']) to empty($_FILES['userfile']['name'])
//if (!isset($_POST[]))
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if(empty($_FILES['userfile']['name'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
}
else {
header('Location: post.php?error');
}
}
else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
}
else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
// $query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
} ?>
I'm getting a blank page with this code:
session_start();
include "config.php";
$af = $_GET['id'];
database_connect();
$query2 = "SELECT * FROM friends WHERE usr1 = '".$id."' AND usr2 = '".$af."'";
$result2 = mysql_query($query2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($result2)) {
if($row2['id']){
echo "<script type='javascript'>alert('You are already friends with this person.');</script>";
header('Location: profile.php?id="'.$af.'"');
}else{
mysql_query("INSERT INTO friends (usr1, usr2)
VALUES ('".$id."', '".$af."')") or die(mysql_error());
echo "<script type='javascript'>alert('You two are friends now!');</script>";
header('Location: profile.php?id="'.$af.'"');
};
};
This is the config.php (i changed the variables here though)
$h = "localhost";
$u = "user";
$p = "pass";
$d = "datab";
$sql = 'SELECT id FROM craffyposts limit '.($page*$eachPage).','.$eachPage;
$sql_count = 'SELECT id FROM craffyposts';
function database_connect(){
global $h, $d, $u, $p;
$link = #mysql_connect("$h","$u","$p");
$sql_error = mysql_error();
if (!$link) {
echo "Connection with the database couldn't be made.<br>";
echo "$sql_error";
exit;
}
if (!#mysql_select_db("$d")) {;
echo "The database couldn't be selected.";
exit;
}
return $link;
}
if($_SESSION['usrid']){
database_connect();
$query = mysql_query("SELECT * FROM craffyusers WHERE id='" .$_SESSION['usrid']. "' ") or die (mysql_error());
while ($obj = mysql_fetch_object($query)) {
$id = htmlspecialchars($obj->id);
$username = htmlspecialchars($obj->username);
$email = htmlspecialchars($obj->email);
$realname = htmlspecialchars($obj->name);
$srvrid = htmlspecialchars($obj->serverid);
$propic = htmlspecialchars($obj->profilepic);
};
};
What's the issue here?
because there will 0 or 1 result, you can remove the while clause:
$row2 = mysql_fetch_assoc($result2);
if($row2 && $row2['id']){
echo "<script type='javascript'>alert('You are already friends with this person.');</script>";
header('Location: profile.php?id="'.$af.'"');
}else{
mysql_query("INSERT INTO friends (usr1, usr2)
VALUES ('".$id."', '".$af."')") or die(mysql_error());
echo "<script type='javascript'>alert('You two are friends now!');</script>";
header('Location: profile.php?id="'.$af.'"');
};
Add this lines at the beginning of the script
error_reporting(E_ALL);
ini_set("display_errors", 1);
The error will appear.