This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.
Related
please help guys i have code for inserting name and etc.. and for inserting a image i cant combine the codes
here is the ouput in phpmyadmin i only insert one value thou...
thanks for your help guys
<---!THIS CODE BELOW IT INSERT ID,NAME AND ETC --->
<?php
require 'db.php';
$message = '';
$Error = '';
if (isset ($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset ($_POST['Status']) ) {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$sql = 'INSERT INTO tbl_listofregister(Attendee_id,
RFID_number,Attendee_Name,CourseOrDepartment,Status)
VALUES(:Attendee_id,
:RFID_number,:Attendee_Name,:CourseOrDepartment,:Status)';
$statement = $connection->prepare($sql);
if ($statement->execute([':Attendee_id' => $Attendee_id, ':RFID_number' =>
$RFID_number,':Attendee_Name' => $Attendee_Name,':CourseOrDepartment' =>
$CourseOrDepartment,':Status' => $Status])) {
$message = 'DATA INSERTED SUCCESSFULLY';
}
else
{
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
<---! HERE IS FOR IMAGE --->
<?php
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('localhost','root','','dbattendancelibrary') or
die('Unable To connect');
$sql = "insert into tbl_listofregister (image) values(?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Image Successfullly UPloaded';
}else{
$msg = 'Error uploading image';
}
mysqli_close($con);
}
?>
This would combine the two inserts into one action. But I would advise against storing the images in the db. Store the path relative to your site of the image instead.
<?php
require 'db.php';
$message = '';
$Error = '';
if(isset($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset($_POST['Status']) &&
isset($_FILES['Image']['tmp_name']) &&
$_SERVER['REQUEST_METHOD']=='POST') {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$sql = 'INSERT INTO tbl_listofregister(
Attendee_id,
RFID_number,
Attendee_Name,
CourseOrDepartment,
Status,
image)
VALUES(:Attendee_id,
:RFID_number,
:Attendee_Name,
:CourseOrDepartment,
:Status,
:Image)';
$statement = $connection->prepare($sql);
if($statement->execute(
[':Attendee_id' => $Attendee_id,
':RFID_number' => $RFID_number,
':Attendee_Name' => $Attendee_Name,
':CourseOrDepartment' => $CourseOrDepartment,
':Status' => $Status,
':Image' => $img]
)) {
$message = 'DATA INSERTED SUCCESSFULLY';
} else {
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
After these lines , you can add this line for an img
move_uploaded_file($_FILES['file']['tmp_name'], "filename/".$_FILES['file']['name']);
Then, add it in the query as ( $_FILES['file']['name'] ).
in HTML file write this line ( ).
I hope it's work well <3
So I am wanting to allow my members to view a profile via a url such as: mywebsite.com/account/Username
however, at the moment my members can view via the url: mywebsite.com/account?username=username.
This doesn't look profesional and I've tried nearly everything to get it to the url I'm looking to get.
(Please be aware; I'm very new to this website and cannot use it properly, If I have done anything wrong, please notify me and I will justify it.)
The code:
//get config
$config = $base->loadConfig();
full code:
https://pastebin.com/UmAmF9Rt
<?php
require('../includes/config.php');
require('../structure/base.php');
require('../structure/forum.php');
require('../structure/forum.index.php');
require('../structure/forum.thread.php');
require('../structure/forum.post.php');
require('../structure/database.php');
require('../structure/user.php');
$database = new database($db_host, $db_name, $db_user, $db_password);
$base = new base($database);
$user = new user($database);
$forum = new forum($database);
$forum_index = new forum_index($database);
$thread = new thread($database);
$post = new post($database);
$user->updateLastActive();
//get config
$config = $base->loadConfig();
//set some variables that are used a lot throughout the page
if (!empty($_GET['username'])) {
$profile_name = htmlspecialchars($_GET["username"]);
}
else{
$profile_name = $user->getUsername($_COOKIE['user'], 2);
}
$username = $user->getUsername($_COOKIE['user'], 2);
$rank = $user->getRank($username);
$f = $_GET['forum'];
$i = $_GET['id'];
//assign data to details[] array
$details['lock'] = $detail_query[0]['lock'];
$details['sticky'] = $detail_query[0]['sticky'];
$details['title'] = stripslashes(htmlentities($detail_query[0]['title']));
$details['username'] = $detail_query[0]['username'];
$details['status'] = $detail_query[0]['status'];
$details['content'] = $detail_query[0]['content'];
$details['date'] = $detail_query[0]['date'];
$details['lastedit'] = $detail_query[0]['lastedit'];
$details['qfc'] = $detail_query[0]['qfc'];
$details['moved'] = $detail_query[0]['moved'];
$details['hidden'] = $detail_query[0]['hidden'];
$details['autohiding'] = $detail_query[0]['autohiding'];
//get forum details
$forum_details = $database->processQuery("SELECT `title` FROM `forums` WHERE `id` = ?", array($f), true);
if(isset($_GET['username'])){
if($user->doesExist($_GET['username'])){;
}
}else{
if(!$user->isLoggedIn()){
$base->redirect('../login.php');
}else{
$user_s = $username;
}
}
$messages = array();
$avatar = $user->getAvatar($profile_user);
$usr = $user->getUsername($profile_user);
if($username == $profile_user && $user->isLoggedIn() && isset($_REQUEST['cust_title'])) {
$user->setTitle($username, htmlentities($_REQUEST['cust_title']));
}
if($user_s == $username && $user->isLoggedIn() && isset($_FILES['uploaded'])) {
if(isset($_REQUEST['delete'])) {
$user->setAvatar($username, '');
$messages[] = "Your avatar has been removed.";
} else {
$ok = false;
$info = getimagesize($_FILES['uploaded']['tmp_name']);
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$messages[] = ("Upload failed with error code " . $_FILES['uploaded']['error']);
} else if($info === FALSE) {
$messages[] = ("Unable to determine image type of uploaded file");
} else if(($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
$messages[] = ("Not a gif/jpeg/png");
} else if($_FILES['uploaded']['size'] > 350000) {
$messages[] = "Your file is too large.";
} else if($_FILES['uploaded']['type'] == "text/php") {
$messages[] = "No PHP files";
} else {
$ok = true;
}
$target = md5(strtolower(trim($username))) .'.'. pathinfo($_FILES['uploaded']['name'])['extension'];
if($ok) {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], "../images/avatar/" . $target)){
$messages[] = "Your avatar has been uploaded. Please allow atleast 10 minutes for it to update.";
$user->setAvatar($username, $target);
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
//retrieve posts/threads
$posts = $database->processQuery("SELECT `id`,`thread`,`username`,`timestamp`,`content` FROM `posts` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
$threads = $database->processQuery("SELECT `id`,`parent`,`title`,`username`,`timestamp`,`content` FROM `threads` WHERE `username` = ? AND ". time() ." - `timestamp` < 1209600 ORDER BY `id` DESC", array($user_s), true);
//type:id:forum:timestamp:(if post)thread
$list = array();
foreach($posts as $post){
//get the thread's forum/parent
$t = $database->processQuery("SELECT `parent` FROM `threads` WHERE `id` = ? LIMIT 1", array($post['thread']), true);
$list[$post['timestamp']] = 'p:'.$post['id'].':'. $t[0]['parent'] .':'.$post['timestamp'].':'.$post['thread'].':'.$post['content'];
}
//add threads
foreach($threads as $thread){
$list[$thread['timestamp']] = 't:'.$thread['id'].':'.$thread['parent'].':'.$thread['timestamp'].':'.$thread['content'];
}
//now sort them
krsort($list, SORT_NUMERIC);
$r = $database->processQuery("SELECT * FROM `users` WHERE `username` = ?", array($profile_name), true);
?>
Your best bet is to use:
.htaccess route with mod_rewrite
Try Adding a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /account.php?username=$username
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want:
Refer to this answer by Niels Keurentjes: https://stackoverflow.com/a/16389034/3367509
If you are new to .htaccess look up this question: What is .htaccess file?
I am making making a dynamic image gallery using PHP, all my CRUD is functioning as expected, except when I update an image's details (title & description), if no new image file i selected, the old one is still deleted.
PHP code is as follows:
$id = null;
if( !empty($_GET['id'])){
$id = $_REQUEST['id'];
}
if( null == $id){
header("location: galleryadmin.php");
}
if (!empty($_POST)){
$uploader = new Uploader();
//keep track of validation errors
$titleError = null;
$descriptionError = null;
$imageError = null;
//track post values
$title = $_POST['title'];
$description = $_POST['description'];
$image = $_POST['image'];
//validating inputs
$valid = true;
if(empty($title)){
$titleError = 'Please add a title';
$valid = false;
}
if(empty($description)){
$descriptionError = 'Please add a description';
$valid = false;
}
if (!empty($_FILES['image']['title']) && !$uploader->valid($_FILES['image'])){
$imageError = 'Invalid file uploaded';
$valid = false;
}
//update data
if($valid){
if (!empty($image)){
$uploader->delete($image);
}
$image = $uploader->upload($_FILES['image']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE gallery set title = ?, description = ?, image = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($title,$description,$image,$id));
Database::disconnect();
header("location: galleryadmin.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM gallery WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$title = $data['title'];
$description = $data['description'];
$image = $data['image'];
Database::disconnect();
}
If the form element called "image" is of type "file" then you can not access it with $_POST['image'] - you can only access it through $_FILES['image']
So your check
if (!empty($image)){
is wrong. Instead, use this
if(is_array($_FILES) AND count($_FILES['image'])!=0 AND $_FILES['image']['error']==UPLOAD_ERR_OK)
Hello everyone i'm taking a value from a URL by get and pass it into an update statement, when i put WHERE ID= 1 , it work fine but when i put the ID=$id, the code work but there is no update, the record remain the same, can some help me to resolve this problem please
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
if (!empty($_POST) ) {
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
echo"error";
}
How about this:
$id = strip_tags(intval($_GET['id']));
mysqli_query($dbc,"UPDATE `movie` SET `Title`='{$title}', `Year` =
'{$year}', `Cast`='{$cast}',
`Cover`='{$actual_image_name}',`Tag`='{$tag}', `Comment`='{$comment}',
`IMDB` ='{$IDBM}' WHERE `MovieID`='{$id}';");
To verify if $id have same value:
echo $id;
It sounds like maybe your MovieID isn't defined as an integer but we can't tell for sure because you haven't told us the error message that mysqli_query is throwing.
You need to be checking the error message created by mysqli_query to know. See http://www.php.net/manual/en/mysqli.error.php
try this
$id = $_GET['id']; // taking the value from URL
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id); // the sql statement of the query
and best you protect the get by using intval() to prevent injections
$id = intval($_GET['id']); // taking the value from URL
So i am having this issue. The code is for art gallery calendar. The code has worked for this day but now it has broken down. I wrote it about 1-2 months ago and now they contacted me that something is wrong. Here is the code
<?php
require('config.php');
if(isset($_POST['lisaa_pvm'])) {
$alkupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['alkupvm'])));
$loppupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['loppupvm'])));
$muuta = mysql_real_escape_string($_POST['muuta']);
$result = mysql_query("INSERT INTO kipina_kalenteri VALUES ('','$alkupvm','$loppupvm','','','','','$muuta')") or die (mysql_error());
$tapahtuma_id = mysql_insert_id();
header('location: lisaa_tapahtuma.php?tid='.$tapahtuma_id);
}
if(isset($_POST['lisaa_tapahtuma'])) {
// siivotaan syƶtteet
foreach ($_POST as $key => $value) {
mysql_real_escape_string($value);
${"$key"} = $value;
}
$url = ROOT.'/files/';
if($_FILES['kuva1']['size'] > 0) {
$target = $url . $_FILES['kuva1']['name'];
if(move_uploaded_file($_FILES['kuva1']['tmp_name'], $target)) {
$kuva[] = "kuva_1 = '".basename( $_FILES['kuva1']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva2']['size'] > 0) {
$target = $url . basename( $_FILES['kuva2']['name']);
if(move_uploaded_file($_FILES['kuva2']['tmp_name'], $target)) {
$kuva[] = "kuva_2 = '".basename( $_FILES['kuva2']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva3']['size'] > 0) {
$target = $url . basename( $_FILES['kuva3']['name']);
if(move_uploaded_file($_FILES['kuva3']['tmp_name'], $target)) {
$kuva[] = "kuva_3 = '".basename( $_FILES['kuva3']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if(isset($kuva)) {
$kuvat = ", ".implode(',',$kuva);
}
if(isset($sama) AND $sama != '') {
$update = "UPDATE kipina_kalenteri SET $paikka = $sama $kuvat WHERE id = $kalenteri";
mysql_query($update) or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} elseif(isset($update)) {
$update = "UPDATE kipina_tapahtuma SET
taiteilija = '$taiteilija',
nimi = '$nimi',
kuvaus = '$kuvaus',
kuvaus = '$lyhyt_kuvaus'
$kuvat
WHERE
id = $update";
$result = mysql_query($update) or die (mysql_query());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} else {
$insert = mysql_query("INSERT INTO kipina_tapahtuma VALUES ('','$taiteilija','$nimi','$lyhyt_kuvaus','$kuvaus','$kuva[0]','$kuva[1]','$kuva[2]')") or die (mysql_error());
$tid = mysql_insert_id();
$update = mysql_query("UPDATE kipina_kalenteri SET $paikka = $tid WHERE id = $kalenteri") or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
}
}
I hope i get answer soon
Someone added or deleted one of the columns in table kipina_kalenteri or kipina_tapahtuma. Because of such situations it's better to always declare to which columns you want to insert.
So it should be like that:
INSERT INTO table (`column1`, `column2`) VALUES ('values1', 'values2');
It's about your table fields. Please define the table field before you start insert a data:
$result = mysql_query("INSERT INTO kipina_kalenteri (`field1`,`field2`,`field3`) VALUES ('$alkupvm','$loppupvm','$muuta')") or die (mysql_error());
so you can sure if the fields are matched with your data