This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I've try to read data from my database but I don't know what it don't work and show me that error
Notice: Array to string conversion in C:\Users\VladxD\Desktop\Xampp\htdocs\Web(workspace)\Test\show_animation.php on line 65
Here is my code:
MySQL_connect:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpassword, "portofoliu_database") or die ("<div id='err'>Could not connect:</div> ");
Code:
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Directory Contents</title>
<link rel="stylesheet" href="show_folder.css">
<link rel="stylesheet" href="NewFile.css">
</head>
<body>
<div id=wapper>
<?php include 'Menu.php';
include 'MySQL_connect.php'; ?>
<div class="box">
<div id="container">
<table class="sortable">
<thead>
<tr>
<th>File name</th>
<th>Uplaod time</th>
</tr>
</thead>
<tbody>
<?php
// Opens directory
$user = #$_SESSION ['account'];
$dir = #$_SESSION ['account'] . '/image/';
if (is_dir($dir) == true) {
$myDirectory = opendir($dir);
// Gets each entry
while ($entryName = readdir($myDirectory)) {
$dirArray [] = $entryName;
}
// Closes directory
closedir($myDirectory);
// Counts elements in array
$indexCount = count($dirArray);
// Sorts files
sort($dirArray);
// Loops through the array of files
for ($index = 0; $index < $indexCount; $index++) {
// Allows ./?hidden to show hidden files
if ($_SERVER ['QUERY_STRING'] == "hidden") {
$hide = "";
} else {
$hide = ".";
}
//-------------------------------------------------------------------------------------------------
//$modtime=date("M j Y g:i A", filemtime($dir.$dirArray[$index]));
$modtime_test = mysqli_query($conn, "SELECT file_upload_time FROM users WHERE file_name ='$dirArray[$index]'");
$modtime = mysqli_fetch_assoc($modtime_test);
$timekey = date("YmdHis", filemtime($dir . $dirArray[$index]));
//-------------------------------------------------------------------------------------------------
if (substr($dirArray [$index], 0, 1) != $hide) {
// Gets File Names
$name = $dirArray [$index];
// Print 'em
echo "
<tr class='file'>
<td><a href=#' onclick='showImage(\"$index\")'>$name</a></td>
<td sorttable_customkey='$timekey'><a href='#'>$modtime</a></td>
</tr>";
}
}
}
?>
</tbody>
</table>
</div>
<div id="imageHolder">
<?php if (is_dir($dir) == false)
echo("<div id = 'noFile'>Your folder it's empty, upload file</div>");
?>
<script>
var array = [
<?php
foreach ($dirArray as $item)
{
echo "\"$dir{$item}\",";
}
?>
];
function showImage(index) {
var url = array[index];
url = "<img src='" + url + "'>";
document.getElementById("imageHolder").innerHTML = url;
}
</script>
</div>
</div>
</div>
</body>
</html>
I want to get my data time from my database and show it on my folder
Here is my element from database: http://i.imgur.com/kYciFQJ.png
and here are my site: http://i.imgur.com/HeEv1yG.png
If you see below "Upload time" I have this text "Array" but I want to get me data time from my database and put there.
As mysqli_fetch_assoc returns an array, not a single value, even if there is a single field being returned... try changing
$modtime = mysqli_fetch_assoc($modtime_test);
to
$results = mysqli_fetch_assoc($modtime_test);
$modtime = $results["file_upload_time"];
You have a PHP notice, "PHP array to string conversion".
<tr class='file'>
<td><a href=#' onclick='showImage(\"$index\")'>$name</a></td>
<td sorttable_customkey='$timekey'><a href='#'>$modtime</a></td>
</tr>";
In that code $modtime is array. You need to use $modtime['file_upload_time'].
Related
Problem:
So when I login, a user can go to the browse.php to add images to the favorites.php, and the photos will appear on that page.
When I log out and log back in, the images are gone (not saved).
Question:
How do I save it after I logout so on next login I get to see the favorite'd images from that particular user using cookies or other methods (can't use database because I'm not allowed to)?
My favorites page
<?php
session_start();
require_once 'favoritesfunction.php';
if (isset($_GET["fileName"])) {
$fileName = $_GET["fileName"];
addToFavorites($fileName);
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
$title = "Travel Photos - View Favorites";
?>
<link rel="stylesheet" href="viewfavorites.css" />
</head>
<body>
<main class="container">
<h1 class="favheader">Favorites</h1>
<div class="content">
<?php
if (isset($_SESSION['favorites']) && isset($_SESSION['email'])) {
$favorites = $_SESSION['favorites'];
if (count($favorites) > 0) {
?> <ul class="ul-favorite"> <?php
foreach ($favorites as $f) {
echo '<img class="displayPic" src="https://storage.googleapis.com/assignment1_web2/square150/' . $f . '">';
}
?>
</ul>
<p id="removeall"><button class="button"><span><a target="" href="services/removefavorites.php?remove=all">Remove All</a></span></button></p>
<?php
}
} else {
?>
<div class="nofavorites">
<p>No favorites found.</p>
</div>
<?php
}
?>
</div>
</main>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
My add to favorites function php
<?php
function addToFavorites($fileName)
{
//Checks if the session favorites exists
if (isset($_SESSION['favorites'])) {
$favorites = $_SESSION['favorites'];
} else {
$favorites = array();
$_SESSION['favorites'] = $favorites;
}
// add item to favourites
$item = $fileName;
$match = false;
//Loop below checks for duplicates
$i = 0;
while ($i < count($favorites)) {
if ($favorites[$i] == $item) {
$favorites[$i] = $item;
$match = true;
}
$i++;
}
//if match equals false, that means its not in the favorites list of the user
//so it is added to the user's favorites array
if ($match == false) {
$favorites[] = $item;
}
$_SESSION['favorites'] = $favorites;
$_SESSION['favorites'] = $favorites;
}
My approach:
I tried doing something like setting $name = $_SESSION['email'] and $value="<img src=...>" then setcookie($name, $value) and then if(isset($_COOKIE[$value])) echo $value
I know this is totally wrong, I tried looking everywhere online to try to solve this, if I could get some help that would be great thanks!
I have a very simple php site that and am attempting to make it a little more dynamic. Previously, I required user to click on a link to open a new page containing several images together with some 'submit' buttons. Pressing a button called a php file that saved some information in a text box. This was working fine. However, I have now made the content a little more dynamic so that the user chooses an item from a popupmenu to update content in the same page. However, now the submit buttons produced dynamically do not seem to work. I am quite new to web development generally so not sure why this should be the case. Any help much appreciated.
This is the index.php file that populates the list box and sets up the page to dynamically manage the content.
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Title</title>
<meta name="language" content="en" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<?php
$myDirectoryStr = "trialImages/";
// open this directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
?>
<?php
// loop through the array of files and print them all in a list
$cnt = 0;
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){
$dateStr[$cnt] = substr($dirArray[$index], 0, 8 );
$cnt++;
}
}
// count elements in array
$indexCount = count($dateStr);
// find unique dates
$dateStrUnique = array_values( array_unique( $dateStr, SORT_STRING ) );
// count elements in array
$indexCount = count($dateStrUnique);
echo '<form>';
echo '<select name="dates" onchange="showImages(this.value)">';
echo '<option value="">select date ...</option>';
for($index=0; $index < $indexCount; $index++) {
echo '<option value="' . $dateStrUnique[$index]. '">' . $dateStrUnique[$index] . '</option>';
}
echo '</select>';
echo '</form>';
?>
<br>
<div id="imageTable"><b> image information will be displayed here ... </b></div>
</body>
</html>
'''
This is the dispData.php file that produces the dynamic content used to update the div tag and containing the submit buttons and images
'''php
<?php
// recover some information
$imageDateTarget = $_GET['imageDate'];
// image directory
$myDirectoryStr = "trialImages/";
// open directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
//count elements in array
$indexCount = count($dirArray);
echo '<table class="fixed">
<col width="200px">
<col width="200px">
<col width="100px">';
// loop through the array of files and display them in table
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){ // input image place in first column
// image date
$imageDate = substr($dirArray[$index], 0, 8 );
// if image date the same as selected date then display image
if ( strcmp( $imageDateTarget, $imageDate ) == 0 ) {
echo '<tr>';
echo '<td>' . $dirArray[$index] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td height=400><img src="' . $myDirectoryStr . $dirArray[$index] . '" class="rotate90" " alt="Image" border=3 height=200 width=400></img></td>';
echo '<form action="writeNotes.php" method="POST">';
//search for matching image notes if they exist and display
$indexImageNotes = array_search( $imageDate . 'notes.txt', $dirArray );
if ($indexImageNotes){
$notes = file_get_contents($myDirectoryStr . $imageDate . 'notes.txt'); // read contents into string
echo '<td><textarea name = "notes" rows = "26" cols="30">' . $notes . '</textarea></td>';
}
else {
echo '<td><textarea name = "notes" rows = "26" cols="30">add some comments here ...</textarea></td>';
}
echo '<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "' . $myDirectoryStr . $imageDate . '"></input></form></td>';
echo '</tr>';
}
}
}
?>
'''
And this is the writeNotes.php function that saves the text notes and should be called when the submit buttons are pressed
'''php
<?php
print_r("I am here");
$file = $_POST["imageDate"] . 'notes.txt';
$data = $_POST["notes"];
file_put_contents($file, $data);
?>
'''
Part of the problem is that I don't get any error messages, just a failure to execute the writeNotes.php function
I think there must be some mistakes in my earlier code as I have attempted a further simplified version and this seems to work. I simply populate a popupmenu below
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="dates" onchange="showImages(this.value)">
<option value="">select date ...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<div id="imageTable"><b> information will be displayed here ... </b></div>
</body>
</html>
'''
And return the dynamic content here
'''php
<?php
echo '<form action="writeNotes.php" method="POST">
<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "a_value"></input></form></td>';
?>
'''
And the writeNotes.php function
'''php
<?php
$file = $_POST["imageDate"];
print_r($file);
//header("Location: index.php"); //note there must be no output before using header
?>
'''
This seems to work without a problem. Apologies for asking the earlier question and thanks again for comments.
Consider a table for example
using these table I just wanted to print a table like these by adding rowspan to item id 1002.
Here is my PHP code
$temp_val = '';
$counter = 1;
$sql_sel = mysqli_query($con,"select * from item_table");
while($res_sel = mysqli_fetch_array($sql_sel)){
if($temp_val == $res_sel['item_id']){
$counter++;
echo "<tr></tr>";
}
else{
echo "<tr><td rowspan='".$counter."'>".$res_sel['item_id']."</td></tr>";
}
$temp_val = $res_sel['item_id'];
}
echo "</table>";
it's not correct, it's adding rowspan to item id 1003
You can't do like this because when you create the first row then you have to decide how much will this column can span so you have to get the count of the similar ids first to achieve it. I am just giving you and idea how it can work with and array like you database provides.
<?php
// Array comming from database
$databaseValues = [
[
'item_id'=>'1001',
'item_color'=>'black',
],
[
'item_id'=>'1002',
'item_color'=>'blue',
],
[
'item_id'=>'1002',
'item_color'=>'green',
],
[
'item_id'=>'1003',
'item_color'=>'red',
]
];
// Creating an array as per the need for the table
$arrayForTable = [];
foreach ($databaseValues as $databaseValue) {
$temp = [];
$temp['item_color'] = $databaseValue['item_color'];
if(!isset($arrayForTable[$databaseValue['item_id']])){
$arrayForTable[$databaseValue['item_id']] = [];
}
$arrayForTable[$databaseValue['item_id']][] = $temp;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table border="1">
<?php foreach ($arrayForTable as $id=>$values) :
foreach ($values as $key=>$value) :?>
<tr>
<?php if($key == 0) :?>
<td rowspan="<?= count($values)?>"><?= $id?></td>
<?php endif;?>
<td><?= $value['item_color']?></td>
</tr>
<?php endforeach;
endforeach; ?>
</table>
</body>
</html>
Hope this will be helpfull for you
You should switch the code inside else and if statement
I am trying to create a PHP file each time a user registers my website. I use the following code to create the file in my register.php :
The thing is, my create file function works but the variable $data doesn't give any result. When I run that $data as a single variable in a different PHP file it still doesn't work.
What did I do wrong about setting the variable.
// STARTING to create a file
$my_file = "$username.php";
$handle = fopen("give/$my_file", 'w') or die('Cannot open file: '.$my_file);
//----------- BEGINNING OF THE PHP DATA TO WRITE TO NEW FILE ----------
$data = "<?
require('../config.inc.php');
$damned_user = $username;
if ( $_COOKIE['damn_given'] != TRUE ) {
$sql = mysql_query(\"SELECT * FROM users WHERE username='$damned_user' LIMIT 1\");
if(mysql_num_rows($sql) == 1){
$row = mysql_fetch_array($sql);
// $row['field'];
$damned_user_id = $row['id'];
if($_SESSION['id'] == $damned_user_id) {
} else {
$taken = $row['taken_damns'];
$taken_damns = $taken + 1;
$taking_sql = \"UPDATE users SET taken_damns='$taken_damns' WHERE username='$damned_user' \";
if (mysql_query($taking_sql)) {
setcookie(\"damn_given\", TRUE, time()+3600*24);
$date = date(\"Y-m-d H:i:s\");
$ip = $_SERVER['REMOTE_ADDR'];
$damns_table = \"INSERT INTO damns (id, from_ip, user_damned, when_damned) VALUES ('','$ip','$damned_user','$date') \";
if ( mysql_query($damns_table)) {
} else {
echo \"Couldn't save damn to damns table in database!\";
}
if ( $_SESSION['logged'] == TRUE ) {
$session_id = $_SESSION['id'];
$giving_sql = \"UPDATE users SET given_damns='$taken_damns' WHERE id='$session_id'\";
if ( mysql_query($giving_sql ) ) {
} else {
echo ('Error giving damn!');
}
}
}
else
{
die (\"Error taking damn!\");
}
}
} else {
die(\"Error first sql!\");
}
}
?>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<link rel=\"stylesheet\" href=\"/_common.css\" />
<link rel=\"stylesheet\" href=\"/_col_white.css\" />
<link rel=\"shortcut icon\" href=\"/favicon.ico\" /> <title>DamnIt.tk - Damned!</title>
</head>
<body>
<div id=\"main\">
<div class=\"center\"><img src=\"/_bnr_white.png\" style=\"width: 500px; height: 100px;\" alt=\"DamnIt Banner\" /></div>
<table class=\"tmid\" style=\"width: 100%;\"><tr>
<td class=\"center\" style=\"width: 25%;\">Profile</td>
<td class=\"center\" style=\"width: 25%;\">Options</td>
<td class=\"center\" style=\"width: 25%;\">Stats</td>
<td class=\"center\" style=\"width: 25%;\">Log out</td>
</tr></table> <h1>Give a Damn</h1>
<?
if ( isset($_COOKIE['damn_given'])) {
?>
<h2>You have already given a Damn to <? echo $damned_user ?> today!</h2><h3>Couldn't damn - try again tomorrow.</h3>
<?
}
elseif ( $_SESSION['id'] == $damned_user_id ) {
?>
<h2>You cannot damn yourself!</h2>
<?
} else{ ?> <h2>Damn given!</h2><h3>You have given a Damn to <? echo $damned_user ?>.</h3> <? } ?>
</div></body>
</html>";
//------- END OF PHP WHICH MUST BE WRITTEN TO NEW FILE ---------
fwrite($handle, $data);
fclose($handle);
// finished with the file
Try NOWDOC:
$data = <<<'END'
Your PHP code here
END;
This will allow for any string, without need for escaping.
However, please consider what you're doing very carefully!
Also... you wouldn't happen to be trying to rip off this site of mine, would you? http://giveadamn.co.uk/
(source: giveadamn.co.uk)
Because if so, you're doing it wrong. .htaccess, mate ;)
RewriteEngine on
RewriteRule give/(.*) give.php?user=$1 [L]
I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their row blue. Any idea how I could do this?
file one:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>High Score</title>
</head>
<body>
form action="data.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Score</td><td><input type="text" name="score"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
Data.php:
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../phpdata/highscore.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$score."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../phpdata/highscore.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Score</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$score) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$score.'</td></tr>';
}
echo '</table>';
?>
Format all players/scores into arrays like array('name' => 'Bob', 'score' => 42):
foreach ($players as &$player) {
list($name, $score) = explode('|', $player);
$player = compact('name', 'score');
}
unset($player);
Sort the array by score (PHP 5.3 syntax):
usort($players, function ($a, $b) { return $b['score'] - $a['score']; });
Output the results, setting a class on the first row:
$first = true;
foreach ($players as $player) {
$class = $first ? ' class="highlight"' : null;
$first = false;
printf('<tr%s><td>%s</td><td>%s</td></tr>', $class, htmlspecialchars($player['name']), htmlspecialchars($player['score']));
}
Now highlight that class using CSS (or do it directly in the HTML, or whatever else you want to do).