Insert array values into mysql database - php

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.

Related

Show selected in multiple selection in PHP loop

I am listing multiple categories.
<?php
function listCategory($id = 0, $string = 0, $catID = 0){
global $sib;
$query = $sib -> prepare( "select * from categories where subCatID=? and isActive=? order by toSort asc" );
$query -> execute( array($id, 1) );
$view = $query -> fetchAll( PDO::FETCH_ASSOC );
$xe = $querye -> rowCount();
if ( $xe ) {
foreach ($view as $row) {
if ( $row["subCatID"] == 0 ) {
echo '<optgroup label="' . $row["title"] . '">';
} else {
echo '<option value="' . $row["categoryID"] . '" >';
}
echo str_repeat( " - ", $string ) . $row["title"];
listCategory( $row["categoryID"], $string + 1, $catID );
if ( $row["subCatID"] == 0 ) {
echo '</optgroup>';
} else {
echo '</option>';
}
}
} else { return false; }
}
listCategory( 0, 0, 0 );
?>
There is no problem with listing. Array contains category ID numbers.
$catIDs = array(4,7,18);
The categories whose id numbers are listed must be selected that are equal to their id number.
I've made a few attempts at this. I could not be successful.
I've made a few attempts at this. I could not be successful.
I solved the problem.
echo '<option value="' . $row["categoryID"] . '" >';
I edited this field
$catListA = array(4,7,18);
$selected = in_array($row["categoryID"],$catListA ) ? "selected" : "";
echo '<option value="' . $row["categoryID"] . '" '. $selected .'>';

Invalid argument supplied for foreach() Comment system

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

Else in foreach looping

What I want if the result is not found from the query select, I want to show else function like:
else {
$html .= 'You have not added stock at all';
}
Because in this case I used string of html, I don't know how to echo the else statement.
More or less my codes is looking like this right now (There are many parts I have removed since it's too long)
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if ($resultsClaim) {
while($obj = $resultsClaim->fetch_object()) {
$orders[$obj->id_cart][$obj->items] = array('status' => $obj->status ...);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) { $html .= '</tr><tr>'; }
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock'.$data['id'].' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: '.$data['method'].' </div>';
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>
Can anyone help me, please! Thanks in Advance.
Since you are taking the no of orders into a variable, you can make use of that directly to see if the orders exists or not.
$orderCount = 0; //Define orderCount in the beginning.
//Rest of the code, till foreach
foreach(){
//Rest of the code here
}
if(intval($orderCount) <= 0) //Using intval, for the case the for loop is not executed at all
{
$html = "Nothing";
}
Here you dont need to concatenate it to $html since you are displaying the table content if order exists or else you displaying "Nothing".
So $html will either have the table content or else "Nothing".
Hope this helps.
First get count of $orders
if (! empty($orders)) {
foreach ($orders AS $order_id => $order) {
// YOUR CODE HERE
}
}
else {
$html .= 'Nothing'; // Append your `no records found` message to the `$html` variable:
}
foreach ($orders AS $order_id => $order) { } else {}
So "}" is missing for foreach loop. Hope it will work for you. Let me know if you need further help.
Give it a try
<?php
include("../actions/config.php");
$resultsClaim = $mysqli->query("SELECT");
$orders = array();
$html = '';
if (!empty($resultsClaim)) {
while ($obj = $resultsClaim->fetch_object()) {
$orders [$obj->id_cart][$obj->items] = array('status' => $obj->status);
}
foreach ($orders AS $order_id => $order) {
$orderCount = count($order);
$html .= '<tbody><tr><td rowspan="' . count($order) . '">' . $order_id . '</td>';
$row = 1;
foreach ($order AS $item => $data) {
if ($row > 1) {
$html .= '</tr><tr>';
}
$html .= '<td>' . $item . '</td>';
$row++;
}
$html .= '<div>
<div class="member-popUpeStock' . $data['id'] . ' member-PopUp">
<div class="member-PopUp-box">
X
<div class="tablePopUp">
<div class="table-row">
<div class="col">: ' . $data['method'] . ' </div>';
}
}
///HERE WHERE I WANT TO DO THAT////
else {
echo 'Nothing';
}
echo $html;
?>

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>';
?>

Last iteration of PHP foreach loop code change

I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}
For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}
Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }
Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}
First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}

Categories