Loop through a session variable with an array value - php

Is there any way to loop a session variable with an array value to insert into the database?
$list_application which where I store the array value
You will see in my code that I've directly insert the $list_application and it returns an Array when I printed it out.
if(isset($_POST['submit'])) {
include('includes/dbconn.php');
$list_application = $_SESSION['LIST_APPS'];
$currUser= getenv("username");
$get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'$list_application', '$list_application','$currUser')";
if($conn->query($get_data) === TRUE ) {
include('includes/dbconn.php');
} else {
echo "Error: " . $get_data. "<br>" . $conn->error;
}
$conn->close();
header('location: summary.php');
}

if I understood your question correctly, then what yyou need is to implode the array to a string that would match the insert:
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
and in you code, notice I changed the INSERT a bit:
if(isset($_POST['submit'])) { include('includes/dbconn.php');
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
$currUser= getenv("username"); $get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'".$list_application. "','$currUser')"; if($conn->query($get_data) === TRUE ) { include('includes/dbconn.php'); } else { echo "Error: " . $get_data. "<br>" . $conn->error; } $conn->close(); header('location: summary.php'); }

Related

Using explode arrays in foreach and only last array Inserted into table, how does arrays work?

I get a text from html-form, didnt mention it here, but it looks like:
John:John
Mike:Mike
Root:Admin
Here is my php code:
$text = explode("\n", $_POST["info"]);
// - get data from html form and //explode it to pieces
print_r($text);
// result is: Array ( [0] => John:John [1] => Mike:Mike [2] => Root:Admin )
foreach ($text as $key => $value) {
$val = explode (":", $value);
// want to explode it to pieces, result must be 0=>John 1=>John, 0=>Mike 1=>Mike, [0]=>Root [1]=>Admin
$sql = "INSERT INTO `redtable`(`NAME`,`NAME2`) VALUES('$val[0]','$val[1]');";
}
When this code runs, it inserts into database only the last line, which are (Root:Admin), why it doesn't inserts John:John, Mike:Mike ...?
Where is the mistake?
Here is the result of echo $sql:
INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('John','John ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Mike','Mike ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Root','Admin');
Here is the full code:
<?php
$servername = "localhost";
$username = "mysql";
$password = "mysql";
$dbname = "red";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$pieces = explode("\n", $_POST["info"]);
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Have trying using if-else statements, like this:
# code...
$val = explode (":", $value);
# print_r($val);
if (1 == 1) {
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
}
else {
echo "esle";
}
}
The same result, only the last line have been inserted to the DB.
GUYS, If SOMEONE NEED THE WORKING SOLUTION WATCH #Matt Rabe answer - working like a charm, you need just replace the brackets!
Mark Baker is right - you are executing your sql outside of your foreach loop. You are defining the $sql var inside your foreach, but the actual execution of it ($conn->query($sql)) occurs outside of the foreach.
Change this:
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
To this:
foreach ($pieces as $key => $value) {
$val = explode (":", $value);
$sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
if ($conn->query($sql) === TRUE) {
echo "Days left updated";
} else {
mysqli_error($conn);
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Your code has numerous issues beyond this, but this should address your stated question.

data insertion into database using json

trying to insert data using json. code executed and each case a blank row is getting inserted instead of the specific given value into the table.. help me to correct this.. the code is given below.
<?php
header('Content-Type: application/json');
include('dbconnect.php');
$json = isset($_POST['submit']) ? $_POST['submit'] : "";
$new = json_decode($json, true);
$sql="INSERT INTO emp(name,address,vicechancellor)
values
('".$new['name']."','".$new['address']."','".$new['vicechancellor']."')";
$res = mysqli_query($con,$sql);
if($res)
{
echo "created ";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>

Call sql query for each value of array in php

I just started learning PHP and wanted to call SQL update query for all the values in the array. But I dont know to execute it in PHP.
<?php
$array = array("12345","23456","34567");
//now here how to call each value of arrayy
foreach ($array as $arr) {
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = '//how to get value of number from array.'";
$result_points1 = $conn->query($sql_points1);
if ($result_points1 === TRUE) {
echo "Current points added ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
In your Foreach loop, the value of the current array element is assigned to $arr, so u can use that in your query.
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = '$arr'";
Please use below code:
<?php
$array = array("12345","23456","34567");
//now here how to call each value of arrayy
foreach ($array as $arr) {
$sql_points1 = "UPDATE user_earning SET points = points + '80' WHERE user_number = $arr";
$result_points1 = $conn->query($sql_points1);
if ($result_points1 === TRUE) {
echo "Current points added ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>

PHP syntax only store last value of the array

need help with this syntax it only stores the last value of my array into the database.
<?php
if(isset($_POST["submit"])) {
$lines=preg_split('/\r\n|[\r\n]/', $_POST['text']);
foreach($lines as $line => $value)
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}
?>
You should add bracket to your foreach. Without that, only the next line will be in the loop.
so you should have:
foreach($lines as $line => $value) {
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
}
}
I advice you to use bracket for all your conditions and loops since the readability is better and you avoid errors like that.
foreach($lines as $line => $value) { // Add braces near foreach
$quer = "INSERT INTO wew (wewe) VALUES('$value')";
if ($conn->query($quer) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $quer . "<br>" . $conn->error;
}
}// close foreach

PHP code execution sequence

I am trying to execute some lines of php code, but it seems that tey are not being execute in the required order. Here is a code snippet:-
if( !empty($_POST['val']) )
{
$val = Get_Val($sid, $_POST['val'], $lnk);
if($val)
{
echo "<br />Here Value : " . $val;
}
else
{
echo "Invalid Value.";
}
}
When I echo the value before returning in function Get_Val() it shows a positive number for some set of valid arguments, which means that the If-condition is true, but when I execute the code the Else part is being executed. Though the output appear in order, they are not consistent. I hope I have made the problem clear.
Any amount of help is appreciated. Thanks!
Here is Get_Val() function:-
function Get_Val( $sid, $a, $link)
{
//check is name is already present in table
$query = "SELECT val FROM store WHERE name = \"" . $a . "\""; //val is auto incremented in sql
$result = mysql_query( $query ,$link ) or die( mysql_error());
if($result)
{
$count = mysql_num_rows($result);
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
Get_Val($sid, $a,$link);
}
}
else
{
$row = mysql_fetch_assoc( $result );
echo "Val in Get_Val : " . $row['val'];
return $row['val'];
}
}
else
{
echo "Unexpected Error Occured...!!!";
exit(0);
}
}
what's with this:
if( $count Val in Get_Val : " . $row['val'];
return $row['val'];
}
are you sure that $_POST['val'] is a valid value that is stored in the db?
Get_Val does not return a value if $count == 0. Add a return statement before the recursive call. Like this:
...
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
return Get_Val($sid, $a,$link);
}
}
...

Categories