Can i use Multiple Array in a foreach loop? - php

I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }

$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.

Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.

After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.

Related

Echo php Variable from Mysql DB

This is my Entire Code:
<?php
$query = "SELECT category FROM html where id = '1' ";
$result = mysql_query($query);
//while loop to display mysql table field values in html text boxes
$i = 0;
while ($row = mysql_fetch_row($result)) {
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
next($row);
$y = $y + 1;
}
$i = $i + 1;
$category = $c_row;
}
echo $category;
?>
I am showing the value of $categories variable using this code given below:
Categories ( '. $categories; .' )
Actaully, the above code including to is not directly written in php
web page. The code "Categories ( '. $categories; .' ) " is containing in the data base. Therefore $categories; cannot be parsed.
What I need is to show the Value:
Eg, if $categories = Books and Shelf;
I need, Categories ( '. $categories; .' ) :- Categories (Books and Shelf)
The $categories; value is already obtained in the php page before selecting from Mysql Table.
How can I parse php variable inserted in Mysql Row?
Categories ( '. $categories; .' ) :- The complete html tag is putted in the data base. The complete html code in the Mysql DB.
I'd like to know why you are storing variable references like that in your db but to solve it you could simply do something like this:
/*
assuming $string contains EXACTLY this
<h4>Categories ( '. $categories; .' ) </h4>
*/
echo str_replace('\'. $categories; .\'',$categories, $string);
If you commonly need to do word replacement on strings stored in a database I would recommend one of the following instead:
1) Use sprintf() and store your string like this:
$string = '<h4>Categories ( %s ) </h4>';
echo sprintf($string, $categories);
2) Use str_replace() and format string with braces around replacements:
$string = '<h4>Categories ( {categories} ) </h4>';
echo str_replace('{categories}', $categories, $string);
The benefit of that last one is you could store all kinds of variable references and replace them accordingly without having to know if they exist in the string:
$string = 'Hello, my name is {firstname} and I live in {city}, {state}';
$replace = ['{firstname}','{lastname}','{address}','{city}','{state}'];
$info = [
'firstname' => 'john',
'lastname' => 'doe',
'address' => '123 main st',
'city' => 'somewhere',
'state' => 'IL'
];
echo str_replace($replace, $info, $string);
OUTPUT: Hello, my name is john and I live in somewhere, IL
A rewrite of your code:
1) Stop using MySQL_ fuctions, they are deprecated, insecure and should not be used. There are two alternatives; mysqli_ functions (Object orientated or Procedural) or PDO functionality (object orientated only)
2) Your question appears uclear, is your <h4> tag within <?php tags or is it just HTML? To output PHP you need to wrap the print/echo article in <?php tags to tell the server how to process this section of the code.
Likewise, you need to be sure the page is pocessed as a PHP page rather than just as an HTML page. So does the page name end with .php (such as page.php)?
3) For clarity: while ($row = mysql_fetch_row($result)) will only ever output one row at a time, each MySQL row with hold numerous columns.
4) It's very useful for you to indent your brackets correctly, typing four spaces (not tab) for each bracket contents, as exampled a litte bit below.
5) Your While loops are confused; you have too any brackets. Your value $c_row will only ever be the final value found in the row, but the row will only ever have one unqiue value in it -- that of the category column, because that's what's specified in the SQL query.
Rewrite:
/***
* Fill with your own values, Address is usually 'Localhost'
***/
// connction details:
$conn = mysqli_connect(Address, User, Password, Database);
// A numeric column (id) does not need values to be quoted.
$query = "SELECT category FROM html where id = 1 ";
// note the mysqli_ and use of new $conn variable setout above
$result = mysqli_query($conn, $query);
/***
* Typical output from the above for returning two rows from
* the DB would be:
* $result[0]['category'] = "whatever_value"
* $result[0][0] = "whatever_value"
* $result[1]['category'] = "whatever_value_row2"
* $result[1][0] = "whatever_value_row2"
***/
// This will fetch all the rows, one row at a time,
// with array keys being the SQL column names
// (ignores numeric array keys).
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// use definite named array key selectors to not need counters.
$category = $row['category'];
echo $category;
}
That would give you an output:
whatever_value
whatever_value_row2
To make your <h4> work as expected you can try replacing your echo with:
print "<h4>Categories ( ". $category; ." ) </h4>";

PHP HTML checkbox only submitting last value MySQL issue

I have a group chat feature on my site and people can add friends by selecting HTML checkboxes, so multiple can be added at one point. However, when my PHP script inserts the data into the MySQL database, only the last value is added. For example, if the user selects 3 friends, PHP separates their ID's by commas (as it will be stored as an array in the database); so it would display like ,1,2,3. However, when I insert into MySQL, only the ",3" is submitting.
PHP code to assemble data from HTML checkbox:
$invite = $_POST['invite'];
if(empty($invite))
{
//echo("You didn't select any friends.");
}
else
{
$N = count($invite);
//echo("You selected $N friends(s): ");
for($i=0; $i < $N; $i++)
{
$userinput = ("," . $invite[$i]);
}
}
MySQL query:
$sql = "INSERT INTO group_chat (title, created_date, last_modified, created_by, user_array) VALUES ('$title', now(), now(), '$logOptions_id', '$logOptions_id$userinput')";
$logOptions_id contains the ID of the current user.
I've echoed the $userinput variable out before and it appears as it should be: ,1,2,3 (comma at the start seperates from current user ID when adding to MySQL.
You are overwriting the values in the loop with this line
$userinput = ("," . $invite[$i]);
Change it to this
$userinput .= ("," . $invite[$i]);
Remember to initialize the the variable $userinput before appending to it to avoid undefined variable warning.
you can create the comma separated id string using implode
$userinput = implode(',', $invite); // output as 1,2,3
If you want to add current user id to it
$userinput = $logOptions_id.','.implode(',', $invite);

How to access an Arrays value by the value of another array

$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
}
This is the structure of my code that I am trying to learn how to properly access... Here is my dilemma... I am trying to figure out how to explicitly find the associated count of nums dependent on the value of a Code.
Let me explain in better detail where my issue is....
Lets say the list of codes is
Code nums
1 624
7 825
571 450
9 393
2 739
9 590
The above code does successfully allow me to separate those values strictly into keys and values but I cannot figure out how to grab the nums value if the code is = to a certain value... I have currently been trying to declare a variable above the entire snippet of code and then declare it within the while statement but cannot figure out how to get the value to bind properly.... I will repaste the above code with one of my many failures in the while statement to give a better idea.
$Answer1 = 0;
$query = "select Code , count(ListID) as nums from accesstable where Cust=" . $_SESSION ['Cust'] . " and App=" . $_SESSION ['App'] . " group by Code";
$result = mysql_query ( $query );
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[] = $row['nums'];
($Codes == 1){
$Answer1 = // Right Here I want to Get the value 624 related to Code 1... Dont want to embarass myself with examples of what I have tried...
}
So how do I make a condition to output the value associated with a Code? I want to explicitly define these values as the list of codes can change with each customer... Luckily there are only a certain amount of codes so its not like I need to define too many of them... I just want to make sure I can get the nums value associated with a code and display it.
Hope I did a good job explaining this. :)
I'd do:
while ($row = mysql_fetch_array ( $result )){
$Codes[] = $row['Code'];
$Values[$row['Code']] = $row['nums'];
}
and, to access the value associated to a code:
$code = 1;
$value = $values[$code];
Since they would share the same array key, something like this would work-
if ($Codes[$key] == 1){
$Answer1 = $Values[$key];
}

Multiple records inserting into MySql from PHP form

I think I've got a tiny mistake in my code so when I try to add two records to MySQL database it adds them both, but at the moment its only adding the second row that should be inputted. SO for example I have two RefTitle fields, two RefSurname fields and so on!
Some PHP Code:
<?php
if(empty($err)) {
for($i = 0; $i < 2; $i++)
{
$RefTitle = $_POST['RefTitle'][$i];
$RefSurname = $_POST['RefSurname'][$i];
$RefForenames = $_POST['RefForenames'][$i];
$RefInstitute = $_POST['RefInstitute'][$i];
$RefEmail = $_POST['RefEmail'][$i];
$RefTelephone = $_POST['RefTelephone'][$i];
$EmailOK = $_POST['EmailOK'][$i];
$sql_insert = "INSERT into `referees`
(`RefTitle`,`RefSurname`,`RefForenames`,`RefInstitute`, `RefEmail`,
`RefTelephone`,`EmailOK`)
VALUES
('$RefTitle','$RefSurname','$RefForenames','$RefInstitute','$RefEmail',
'$RefTelephone','$EmailOK'
)
"; ?>
I have the [] after each name field in my html form.
Thanks
Here's what I think is happening.
In the loop, you're adding the current query to a string, overwriting the previous query. After the loop ends, you run mysql_query but this will only run on the last query generated by the loop.
You have two ways to fix this:
Execute the query within the loop on every iteration. Pseudo code:
for ($i = 1 to 100)
{
$query = //build your query;
mysql_query($query);
}
Alternatively, (and the better way) is to use a value list in your insert statement.
An insert with a list of values looks like this
INSERT INTO table VALUES (1,2,3), (4,5,6), (7,8,9)
So, (pseudo code again)
$query = "INSERT INTO table VALUES ";
for ($i = 1 to 100)
{
$query .= " (";
$query .= "" //comma seperate the values of the current iteration
$query .= "),";
}
//after loop ends, remove the trailing extraneous comma
// execute the entire query at once
mysql_query($query);

MySQL INSERT - Using a for() loop with query & do non-set values insert as "" by default?

I have two arrays with anywhere from 1 to 5 set values. I want to insert these values into a table with two columns.
Here's my current query, given to me in another SO question:
INSERT INTO table_name (country, redirect)
VALUES ('$country[1]', '$redirect[1]'),
('$country[2]', '$redirect[2]'),
('$country[3]', '$redirect[3]'),
('$country[4]', '$redirect[4]'),
('$country[5]', '$redirect[5]')
ON DUPLICATE KEY UPDATE redirect=VALUES(redirect)
I'm a little concerned however with what happens if some of these array values aren't set, as I believe the above assumes there's 5 sets of values (10 values in total), which definitely isn't certain. If a value is null/0 does it automatically skip it?
Would something like this work better, would it be a lot more taxing on resources?
for($i = 0, $size = $sizeof($country); $i <= size; $i++) {
$query = "INSERT INTO table_name (country, redirect) VALUES ('$country[$i]', '$redirect[$i]) ON DUPLICATE KEY UPDATE redirect='$redirect[$i]'";
$result = mysql_query($query);
}
Questions highlighted in bold ;). Any answers would be very much appreciated :) :)!!
Do something like this:
$vals = array()
foreach($country as $key => $country_val) {
if (empty($country_val) || empty($redirect[$key])) {
continue;
}
$vals[] = "('" . mysql_real_escape_string($country_val) . "','" . mysql_real_escape_string($redirect[$key]) . "')";
}
$val_string = implode(',', $vals);
$sql = "INSERT INTO .... VALUES $val_string";
That'll built up the values section dynamically, skipping any that aren't set. Note, however, that there is a length limit to mysql query strings, set by the max_allowed_packet setting. If you're building a "huge" query, you'll have to split it into multiple smaller ones if it exceeds this limit.
If you are asking whether php will automatically skip inserting your values into the query if it is null or 0, the answer is no. Why dont you loop through the countries, if they have a matching redirect then include that portion of the insert statement.. something like this: (not tested, just showing an example). It's one query, all values. You can also incorporate some checking or default to null if they do not exist.
$query = "INSERT INTO table_name (country, redirect) VALUES ";
for($i = 0, $size = $sizeof($country); $i <= size; $i++) {
if(array_key_exists($i, $country && array_key_exists($i, $redirect)
if($i + 1 != $size){
$query .= "('".$country[$i]."', '".$redirect[$i]).",";
} else $query .= "('".$country[$i]."', '".$redirect[$i].")";
}
}
$query .= " ON DUPLICATE KEY UPDATE redirect=VALUES(redirect);"
$result = mysql_query($query);

Categories