php inserts only last array record into sql - php

I have working code, which inserts data into csv file. Here is a part of it:
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$txt = $txt . $loop['name'] . ";" . $loop['email'];
$txt .="\n";
}
}
Instead of csv, i would like it to insert data into mysql database, so i have simply changed the code to:
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
}
}
Only the last record is saved into the persons table. There are no errors, but all the previous records except last are not inserted. Why?

Better way is only one time create insert
if (isset($_POST['array'])) {
$values = [];
$sql = "insert into persons (Name, Email) values ";
foreach ($_POST['array'] as $loop) {
$values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";
}
if (!empty($values)) {
$conn->query($sql . implode(', ', $values));
}
}

The reason why it doesn't work is because you never execute your SQL query anywhere.
To execute the query you should first prepare the statement and then bind the params and execute.
// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['array'])) {
$stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
foreach ($_POST['array'] as $loop) {
$stmt->bind_param('ss', $loop['name'], $loop['email']);
$stmt->execute();
}
}

Please execute query inside the loop as given below
...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
$conn->query($sql);// Query should execute inside loop
}
}

I had the same issue inserting JSON arrays into MySQL and fixed it by putting the mysqli_stmt->execute() function inside the foreach
// loop through the array
foreach ($data as $row) {
echo "Data has been Uploaded successfully <br>";
// get the project details
$id = $row['id'];
$name = $row['name'];
$togglCid = $row['cid'];
// execute insert query
mysqli_stmt_execute($sql);
}
This means it executes the code after each loop

If you want to execute the query outside the loop
Try using as following
if (isset($_POST['array'])) {
$sql="";
foreach ($_POST['array'] as $loop) {
$sql .= "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";
}
}

Related

How to get logged person's user_id from the database and match the user id session with the second table as the foreign key?

$sql = "INSERT INTO useraccounts (name, email, taman, password) VALUES ('" . $_POST['name'] . "', '" . $_POST['email'] . "', '" . $_POST['taman'] . "','" . $_POST['passsword'] . "')";
if ($db->query($sql)) {
$id = $db->insert_id;
$query = "";
$count = count($_POST['barang']);
for ($i = 0; $i < $count; $i++) {
$query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName',
'$id')";
}
if ($db->multi_query($query)) {
echo
"<script>
alert('Successfully Added!');
document.location.href = 'displayRequest.php';
</script>";
} else {
echo "Failed";
}
} else {
echo "Failed";
}
Here is my current code. I would like to seek for help on how can I fix this code in order to insert data in second table by using current user id session as its foreign key in that second table?
First thing in this code:
for($i=0; $i<$count;$i++){
$query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName',
'$id')";
}
You maybe wanted to use .= instead of just =. And use ; at the end of sql query.
+be carefull with inserting user data to sql. Escape it to prevent SQL injections!

Json data getting read but not inserting into mysql using php

Im trying to insert json data using php into mysql,
I get success msg, but no records are inserted.
My json data is :
jsondata.json:
{"users": { "bert":6.44, "earnie":0.25, "bigbird":34.45 }}
My php code:
<?php
//First: read data
$fo=fopen("data.json","r");
$fr=fread($fo,filesize("data.json"));
$array=json_decode($fr,true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//To display all values from JSON file
echo '<pre>';print_r($array);
//Save to DB
$hostname = 'localhost';
$username = 'root';
$password = '';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />';
//$count = $dbh->exec("INSERT INTO USERSAMOUNTS(USERNAME, AMOUNT) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
$count = $dbh->exec("INSERT INTO json(firstName) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
echo 'Success<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I believe the problem could be the order in which the actions are performed.
<?php
//First: read data
$fo = fopen("jsondata.json", "r");
$fr = fread($fo, filesize("jsondata.json"));
$array = json_decode($fr, true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//Third: display
echo '<pre>';
print_r($array);
//Fourth: save to db
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
echo $count; // echo the number of affected rows
$dbh = null; // close the database connection
echo 'Success<br />';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them for more info please check - http://php.net/manual/en/pdo.setattribute.php
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
Hope this help.
The issue is with how your are trying to insert data. I'm surprised you're not getting an error.
You should use a prepared statement. See the following... https://stackoverflow.com/a/4629088/2033178
Some things are funky here.
At first it looks like you're expecting the data to come magically from $data (unless that is passed somewhere?)
$array = json_decode($data, true);
$rows = array();
foreach($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
And then it looks like you're opening a file and parsing the JSON (but not doing the above magic with $rows[])
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
Why not insert on the for each loop?
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
$count = 0;
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
try {
foreach($array['users'] as $key => $value)
$count = $count + $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $key . " " . $value . ")";
} catch ...

Insert an array to MySQL database using PHP's prepared statements

I have an input array that I want to insert to database. I don't want to have 1 row in database for each item in the array. I want them all to go on same row. So this is my code:
<?php
session_start();
include('../../config/dbconf.php');
mysqli_select_db($conn, $webdb);
$stmt = $conn->prepare("INSERT INTO changelog (title, type, content, author, post_date) VALUES (?, ?, ?, ?, ?)");
$title = $_POST['title'];
$type = $_POST['type'];
$change = $_POST['change'];
$author = $_SESSION['waradmin'];
$date = time();
foreach($_POST['change'] as $key => $value) {
$changes = "<li>" . $change[$key] . "</li>";
}
$stmt->bind_param("sissi", $title, $type, $changes, $author, $date);
if($stmt->execute()) {
header('location: ../?p=dashboard');
}else{
echo "Error: " . $stmt->error;
}
$stmt->close();
?>
The query runs in database but only the first list item from the array... Do I need to use the implode function? I have never used it so if that is the only solution can someone show me how i use that in this query?
Instead of replacing variable value you have to concatenate
$changes = '';
foreach($_POST['change'] as $key => $value) {
$changes .= "<li>" . $change[$key] . "</li>";
}
And this is how to make a little more clean:
$changes = '';
foreach($_POST['change'] as $value) {
$changes .= '<li>' . $value . '</li>';
}

Checking Table exists before inserting php sql

I am trying to check if a table exists before entering the data into it. I am trying mysql_query and getting errors that I should be using mysqli, but it does not seem to be working for me.
This is my code so far:
$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
// Insert into database tuple data
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
Try this way to check table exists or not using this custom function and then insert row to your db.
function check_table_exist($table){
global $dbConnection; // see here global connection variable
$sql = "SHOW tables LIKE '".$table."'";
$res = $dbConnection->query($sql);
return ($res->num_rows > 0);
}
#check first table exists or not
if(check_table_exists($table)){
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
//do other stuff........
}else{
echo "Table Not Exists";
die('Going Out');
}
Table name is accepted as POST parameter, seriously !! - bad practice.
You can do various check to table existence like
DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

Create and insert variables into mysql from for loop using php

I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!

Categories