Invalid argument supplied for foreach() Comment system - php

First of all my English language is not perfect so try to explain my problem at my best. So i have a problem with Invalid argument supplied for foreach() and i have no idea what's wrong. I wanted to create a comment system where i can put a reginstered users. If you have any ideas or working comment system where i could use my data base with users i would be grateful.
Here is my code
<?php
function get_comments($file_id) {
require 'polaczenie.php';
$result = "SELECT * FROM `comments` WHERE `file_id`='$file_id' AND `is_child`=FALSE ORDER BY `date` DESC";
$row_cnt =mysql_query($result);
echo '<h1>Comments ('.$row_cnt.')</h1>';
echo '<div class="comment">';
new_comment();
echo '</div>';
foreach($result as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$auth = $item['author'];
$par_code = $item['com_code'];
$chi_result ="SELECT * FROM `comments` WHERE `par_code`='$par_code' AND `is_child`=TRUE";
$chi_cnt = mysql_query($chi_result);
echo '<div class="comment" name="'.$item['com_code'].'">'
.'<span class="author">'.$auth.'</span><br />'
.$item['comment'].'<br />'
.'<span class="date">Posted: '.$date.'</span><br />';
if($chi_cnt == 0) {
echo '<span class="replies">No replies</span>'
.'<span class="replies"> Reply</span>';
} else {
echo '<span class="replies">[+] '.$chi_cnt.' replies</span>'
.'<span class="replies" Reply</span>';
add_comment($item['author'], $item['com_code']);
echo '<div name="children" id="children">';
foreach($chi_result as $com) {
$chi_date = new dateTime($com['date']);
$chi_date = date_format($chi_date, 'M j, Y | H:i:s');
echo '<div class="child" name="'.$com['com_code'].'">'
.'<span class="author">'.$com['author'].'</span><br />'
.$com['comment'].'<br />'
.'<span class="date">Posted: '.$chi_date.'</span><br />'
.'</div>';
}
echo '</div>';
}
echo '</div>';
}
mysql_close($conn);
}
function add_comment($reply, $code) {
echo '<form action="reply.php" method="post" enctpye="" name="new_comment">'
.'<input type="hidden" name="par_code" value="'.$code.'" />'
.'<textarea class="text_cmt" name="text_cmt" placeholder="Reply to '.$reply.'"></textarea><br />'
.'<input type="submit" value="Reply" />'
.'</form>';
}
function new_comment() {
echo '<form action="new.php" method="post" enctpye="" name="new_comment">'
.'<textarea class="text_cmt" name="text_cmt" placeholder="Post a new comment"></textarea><br />'
.'<input type="submit" value="Post" />'
.'</form>';
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characterLength = strlen($characters);
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $characterLength - 1)];
}
return $randomString;
}
function checkString($com_code) {
include 'database.php';
$rand = generateRandomString();
$result ="SELECT * FROM `comments` WHERE `com_code`='$com_code'";
$row_cnt = mysql_query($result);
if($row_cnt != 0) {
return $rand;
} else {
checkString($rand);
}
}
?>

Probably
foreach($result as $item) {
should be
foreach($row_cnt as $item) {
You are passing to the foreach function the query string.

Here, $result is just a variable containing your query. foreach loop requires an array or object which it can traverse. You should use while loop instead.
Example Scenario:
$result = "SELECT * FROM `comments` WHERE `file_id`='$file_id' AND `is_child`=FALSE ORDER BY `date` DESC";
$comments = mysql_query($result);
while($comment = mysql_fetch_array($comments))
{
//Do whatever you want with your each comment
}
I hope this will help :)
Or you can follow steps from here W3schools mySql Select with php while loop

Related

I can't substitude values to a placeholder of SQL statement

I tried to separate SQL's data with the following code:
$count = $pdo->query('SELECT COUNT(*) FROM tweets');
foreach ($count as $row) {
$num = $row[0];
echo 'count:'.$row[0].'<br>';
}
echo 'num value: '.$num.'<br>';
$max_page = ceil($num / 10);
echo 'page: '.$max_page.'<br>';
if (!isset($_GET['page'])) {
$_GET['page'] = 1;
} else {
$now = $_GET['page'];
echo '$_GET has been set successfully<br>';
}
$disp_start = $num - 10 * ($now - 1);
echo 'disp_start value: '.$disp_start.'<br>';
$disp_end = $num - 10 * $now;
echo 'disp_end value: '.$disp_end.'<br>';
$disp = $pdo->prepare('SELECT * FROM tweets ORDER BY id DESC LIMIT 10 OFFSET ?');
//$disp -> bindValue(':st', $disp_start);
//$disp -> bindValue(':en', $disp_end);
if ($disp->execute([$disp_end])) {
echo 'success!';
foreach ($disp as $row) {
echo '<div class="breakwater2">';
echo '<div class="tweet">';
echo '<a href="./user/'.$row['uploader'].'.php">';
echo '<img src="', $row['avatar'], '" class="avatar1">';
echo '<div class="cont">';
echo '<b class="username">', $row['uploader'], '</b></a>';
echo '<p class="contents1">', $row['contents'], '</p>';
echo '<p class="time">', $row['time'], '</p>';
echo '</div>';//cont
echo '</div>';//tweet
echo '<form action="" method="post"><input type="hidden" name="del" value='.$row['id'].'>';
if ($_SESSION['user']['id'] == $row['userid']) {
echo '<input type="submit" value="Delete">';
}
echo '</form>';
echo '</div>';
echo '<hr class="division">';
}
} else {
echo 'failure';
print_r ($disp -> errorInfo());
}
for ($i = 1; $i <= $max_page; $i++) {
if ($i == $now) {
echo $now;
} else {
echo ''.$i.'';
}
}
However, when I execute this code an error occurs and it says
failureArray ( [0] => 42000 [1] => 1064 [2] => 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 ''53'' at line 1
But, if I don't use a placeholder and substitute a value directly to the 'OFFSET' value, it works. How can I solve it?

Insert array values into mysql database

The variables are being posted from a previous page through array values.
when I print_r($values) I get the whole value on this array including the numerical values of the array ex: array[0], array[1] ..etc.
Please can some tell me what I am doing wrong. the implode function was not used because the values are passed from a cart page though session variables.
First part of code below:
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT Title,Description,Price FROM main_menu WHERE MenuID='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->Price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->Title.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->Description.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->Description.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '<input name=\'submit\' type="submit" value="Complete Order" style=\"width:150px;background:#333;color:#ffcc33;height:30px;\" />';
echo '</span>';
echo '</form>';
}else{
echo 'No items added';
}
?>
Second part:
Try $post and the table name in the given function and use mysql_real_escape_string() to avoid any possibility of the SQL Injection
form.php
<?php
include ('func_curd.php') ;
if($_POST['hiddenfieldinfo']=='ok')
{
$r=insert_your_table_name($_POST);
if($r==true)
{
header('Location:'.get_full_url()); /* to redirect the form to the same page after successful submission*/
}
}
?>
func_curd.php
<?php
function insert_your_table_name($post)
{
unset($post['hiddenfieldinfo']);
/* Here I am unsetting this value as it is hidden field
in the form , which I am using as form submission check and
is not in database column, apart form auto-increment in database
that is id, you have to maek sure all the post value and column
name matches with case-sensitivities */
$u = insert('your_table_name', $post);
$r=is_numeric($u)? true : false ;
return $r;
}
function insert($table, $values){
$query="INSERT INTO `$table` ";
$column='(';
$val=' (';
$count=count($values);
$mk=1;
foreach ($values as $key=>$value)
{
$value=mysql_real_escape_string($value);
if ($mk==$count)
{
$column .= '`'.$key.'`';
$val .= "'".$value."'";
}
else
{
$column .= '`'.$key.'`, ';
$val .= "'".$value."', ";
}
$mk++;
}
$column .=') ';
$val .=')';
$query=$query.$column.'VALUES'.$val;
$Q=mysql_query($query);
if(mysql_error())
{
return print(mysql_error());
}
else
{
$insert_id=mysql_insert_id();
return $insert_id;
}
}
?>
try this one:
<?php
require_once('config/connect.php');
$item_name = strip_tags($_POST['item_name']);
$item_code = strip_tags($_POST['item_code']);
$item_desc = strip_tags($_POST['item_desc']);
$item_qty = strip_tags($_POST['qty']);
$price = strip_tags($_POST['price']);
$fields = "item_name, item_code, item_desc, price,qty";
$query = "INSERT INTO `x` SET ";
$i = 0;
foreach( $fields as $fieldname )
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $fieldname . "` = '" . $val . "'"
$i++
}
$query_result = mysql_query($query);
echo" Record saved";
print_r ( $query );
?>
There are certain syntax errors in your code like not closed foreach etc. whihc I did skip.
As a recommendation: code like this is disclosing the database structure to everyone on the internet - form field names = database col names. This is generally a bad idea.
Better is a kind of mapping table:
$fields = array (
'myFormName' => 'mySqlName',
....
foreach( $fields as $fieldname => $sqlame)
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $sqlname. "` = '" . $val . "'"
....
which also will make the form more independent from the underlying data structures.

PHP getting days of a month for a database

I'm making a calender planner with php/css/javascript/html.
I am trying to set each day of the month a class which is "day". I tried using the following:
**PHP CODE**
error_reporting(E_ALL);
ini_set('display_errors', '1');
include "scripts/connect_to_mysql.php";
$jobNameValue ='';
$monthDays = '';
$monthname = '';
$days = '';
//getting values for job names
$sql_job_name = mysql_query("SELECT * FROM jobs");
$num_job_name = mysql_num_rows($sql_job_name);
if($num_job_name >0) {
while ($row = mysql_fetch_array($sql_job_name)) {
$job_name = $row["job_name"];
$job_short_name = $row["job_short_name"];
$jobNameValue .= '<option value="' . $job_short_name . '">' . $job_name . '</option>';
}
} else {
$jobNameValue .= '<option value="NULL">No job listed</option>';
}
//getting values for months days
$sql_month_days = mysql_query("SELECT * FROM months");
$num_month_days = mysql_num_rows($sql_month_days);
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
$month_id = $row["id"];
$name = $row["name"];
$num_days = $row["num_days"];if($num_days === "31") {
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
$monthDays .= '<div id="monthContainer">
<span class="monthName">'. $name .'</span>
<div class="monthDaysContainter">
'. $days.'
</div>
</div>';
}
}
**HTML CODE**
<div id="container">
<div ="newJob">
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="newJobForm">
<label for="jobName">Job Name:</label>
<select id="jobName">
<?php echo $jobNameValue; ?>
</select>
<input type="date">
<input type="submit" id="submit">
</form>
</div>
<div id="calander">
<?php echo $monthDays; ?>
</div>
</div>
It does not work correctly, it kept duplicating every month and I am not sure how to correctly right the php to achieve what was intended.
I am only a beginner at php so I am not good at the moment
Could anyone help me with this?
If there any more information you need, please don't hesitate to ask.
Thank you in advance!
Chris
Try just doing this and seeing if that fixes it, you don't need all of those if statements
for($i=1; $i <= $num_days; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
do not use ===,use ==,maybe your $num_days is integer
Your problem is that you are creating the whole thing in the while loop, so the days that are appended from the last call are also appended to the next output.
$tmpArray = array();
if($sql_month_days > 0) {
while($row = mysql_fetch_array($sql_month_days)) {
array_push($tmpArray, $row);
}
}
foreach($tmpArray as $k){
$monthDays .= '<div id="monthContainer"><span class="monthName">'. $k['name'] .'</span><div class="monthDaysContainter">'. calNumDays($k['num_days']).'</div></div>';
}
Update
Should you wish to keep what you already have
if($num_days === "31") {
$days = '';
for($i=1; $i <=31; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "30") {
$days = '';
for($i=1; $i <=30; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
} else {
if($num_days === "29") {
$days = '';
for($i=1; $i <=29; $i++) {
$days .= '<span class="day">' . $i . '</span>';
}
}
}
}
You only really to need to reinitialize the $days before each for after the if

Images from database column not loading

CODE:
<?php
$page = $_GET['page'];
$category = $_GET['cat'];
$your_db = # new mysqli("database","name","password");
if (mysqli_connect_errno())
{
echo 'ERROR!
'.mysqli_connect_errno()
.' - Not connected : '.mysqli_connect_error().'
';
die;
}
else
{
$db_connect = $your_db->select_db("databasename");
if (!$db_connect)
{
echo 'ERROR CONNECT DATA BASE';
die;
}
}
echo '<p>';
$query = "select distinct fldCity from info order by fldCity";
$result = $your_db->query($query);
$number_of_records = $result->num_rows;
for ($i = 0; $i < $number_of_records; $i++)
{
$row = $result->fetch_assoc();
echo '<a href="index.php?cat='.stripslashes($row['fldCity']).'">';
echo stripslashes($row['fldCity']);
echo '</a> / ';
}
echo '</p>';
if ($category)
{
$query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
from info where fldCity = '$category' and length(fldCompanyLogo) > 0 order by fldCity";
}
else
{
$query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
from info where length(fldCompanyLogo) > 0 order by fldCity";
}
$result = $your_db->query($query);
$number_of_records = $result->num_rows;
$num_pages = $number_of_records / 7;
if (($number_of_records % 7) > 0 )
{
$num_pages++;
}
if (strlen($page) == 0)
{
$page = 0;
}
else
{
$page = $page * 4;
}
echo '<table border="0" cellspacing="10" cellpadding="10" style="border-collapse: collapse" bordercolor="#111111">';
$row_num = 4;
$result->data_seek($page);
for ($i = $page; $i < $number_of_records; $i++)
{
if ($row_num <= 4)
{
echo '<tr>';
for ($col_num = 0; $col_num < 4; $col_num++)
{
$row = $result->fetch_assoc();
echo '<td>';
show_image(stripslashes($row['fldCompanyLogo']),stripslashes($row['fldCompanyName']));
echo '
';
echo '<b><font face="Tahoma" size="2"><a href="mysite.ca/'.stripslashes($row['fldMenuLink']).'" target="_blank"></font>';
echo '<font face="Tahoma" size="2"><a href="'.stripslashes($row['fldMenuLink']).'" target="_blank">';
echo stripslashes($row['fldCompanyName']);
echo '</a>';
echo '
';
echo stripslashes($row['fldCity']);
echo '
';
echo stripslashes($row['fldProvince']);
echo '
';
echo stripslashes($row['fldPostalCode']);
echo '</td>';
}
$row_num++;
echo '</tr>';
}
else
{
break;
}
}
echo '</table>';
for ($j = 0; $j < $num_pages; $j++)
{
$page_link = $j + 1;
echo '<font face="Tahoma" size="4"><b>'.$page_link.'</b></font> ';
}
echo ' '.$number_of_records;
function show_image($image_name)
{
if (file_exists("'$image_name'"))
{
$dim_img = getimagesize('/images/'.$image_name);
echo '<img src="/images/'.$image_name.'" alt = '.$alt.' border=0 align="bottom"';
echo 'width = '. $dim_img[100] .' height = ' .$dim_img[100] . ' />';
}
else
echo 'Add your image here!';
}
?>
I am totally lost and I can't find the error to why the images from the database isn't loading with the script. I highlighted the area in blue where I believe the error is to be. I just can't find any errors in that particular spot! All I want is the images from a column I have in my database to be fetched and connected to 'echo '
No images are being displayed, and I can't find the error as to why the images aren't showing up
try Convert Image to Base64 String and Base64 String to Image
also why echo ''; you use this its makes no sense

PHP & MySql | Add Extra DIV If The Number Of Sql Rows Exceeds A Given Number

I have the following PHP function which will list the users from a MySql table and will print the HTML code as you can see:
//List All Users From The Database Table In An Array
public function listUsersInArray() {
$sql = "SELECT username FROM user";
$users = array();
if($stmt = $this->conn->prepare($sql)) {
$stmt->bind_result($usrn);
$stmt->execute();
while ($row = $stmt->fetch()) {
$stmt->bind_result($usrn);
$users[] = $usrn;
}
$stmt->close();
return $users;
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "The Users Could Not Stored In Array";
return json_encode($message);
}
}
//Build A Form In Order To Print Out The Users For Deleting
private function createForm($id) {
$form = array( '<form name="delete-user" id="'.$id.'" class="delete-user" method="post" action="#">',
'<input type="hidden" name="user_id" value="'.$id.'" />',
'<fieldset class="user-wrapper">',
'<label for="user" class="user-label">User</label>',
'<input type="text" name="user" class="user" value="'.$id.'" autocomplete="off" readonly="readonly" />',
'</fieldset>',
'<fieldset class="delete-wrapper">',
'<button type="submit" name="delete" class="delete">Delete</button>',
'</fieldset>',
'</form>'
);
$form = implode("",$form);
return $form;
}
//List All Users From Array As Forms For Deleting
public function listUsersForDelete() {
$users = $this->listUsersInArray();
for ($i = 0; $i < sizeof($users) ; $i++) {
while((sizeof($users) <= ($i % 7 == 0 || $i == 0))) {
echo $this->createForm($users[$i]);
$i++;
}
}
}
And now I just have to figure out how to add a wrap the all the forms in a div if the forms are more than 7 and do that each time I encounter a multiple of 7.
For example, if I have 9 forms, wrap the first 7 in a div but also wrap the rest in another div, and if I have 16 forms, wrap the first 7 in a div, the next 7 in a div and the rest of 2 in another div, and so on ...
You suggested code looks fine. The only thing I would suggest is that you store the <form> code into a variable first instead of just copying and pasting it. Copying and pasting is prone to a lot of errors, especially if you have to update the code later.
Modulus would work but you may want to use an array to easily enclose the forms in divs if it's greater then 7 results.
Try adapting this script as it displays results in a table grid view.
<?php
echo '<table>';
$number_of_thumbs_in_row = 2;
$result = mysql_query("");
$nr = mysql_num_rows($result);
if (empty($nr)) {
$result_final = "\t<tr><td></td></tr>\n";
} else {
while ($row = mysql_fetch_array($result)) {
$result_array[] = "<tr>your data</tr>";
}
$result_final = "<tr>\n";
foreach ($result_array as $thumbnail_link) {
if ($counter == $number_of_thumbs_in_row) {
$counter = 1;
$result_final .= "\n</tr>\n<tr>\n";
} else
$counter++;
$result_final .= "\t<td>" . $thumbnail_link . "</td>\n";
}
if ($counter) {
if ($number_of_photos_in_row - $counter)
$result_final .= "\t<td colspan='" . ($number_of_photos_in_row - $counter) .
"'> </td>\n";
}
$result_final .= "</tr>";
}
echo $result_final;
echo '</table>';
?>

Categories