Stored array data into string with comma(,) - php

[!]problem: whenever I get the data from frontend and try to insert into database...the data are inserted as a single alphabet in elective cell...but what I really needed that the whole data to be inserted in the elective cell with separated by comma(,)
<?php
include_once '../../config/db_connection.php';
include_once '../../config/functions.php';
include "autho.php";
include('../db_mysqli.php');
if (isset($_POST['submit'])) {
$username1 = $_POST['username'];
$username1 = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $username1);
$rollno = $_POST['register_no'];
$rollno = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $rollno);
$subjectcode = implode(',', $_POST['subject']); ;
date_default_timezone_set("Asia/Kolkata");
$today = date('g:ia \o\n l jS F Y');
$rollnos = array_map('strlen', $rollno);
$rollnos = min($rollnos);
if ($rollnos < 6) {
$error = 'Roll Number is too short.';
} else {
}
if (!isset($error)) {
for ($i = 0; $i < count($rollno); $i++) {
$sql = "UPDATE students SET elective='$subjectcode[$i]' WHERE register_number='$rollno[$i]'";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location:./?edu_camp=elective_student_update&success');
} else {
header('Location:./?edu_camp=elective_student_update&fail');
}
}
} else {
//echo "Sorry! something Wrong.";
}
}
?>

As the comments mentioned, you can implode your array into a string an insert it (docs).
Also, you're using MySQLi, but not using bound parameters which you REALLY should be using (docs).
// Concatenate all values together
$commaSeparatedList = implode(',',$subjectcode);
// Prepare your statement
$stmt = $mysqli->prepare("UPDATE students SET elective=? WHERE register_number=?");
// Bind the relevant parameters (not sure what the where clause should be here)
$stmt->bind_param('si', $commaSeparatedList, $i);
// Check if rows were affected
if ($mysqli->affected_rows > 0) {
// Success, rows were changed
}
// Execute and close the statement object
$stmt->execute();
$stmt->close();

Related

How to update records when importing csv file [duplicate]

This question already has answers here:
How to use mysqli prepared statements?
(3 answers)
Closed 8 months ago.
I want to update existing records in a table using an excel csv import file.
the table name is aflossingen and has the columns: AflossingID, VoorschotID, Aflossingdatum, Aflossingsbedrag, Afgelost, Saldo.
This is the code PHPRad has generated, which can only do an INSERT:
function import_data(){
if(!empty($_FILES['file'])){
$finfo = pathinfo($_FILES['file']['name']);
$ext = strtolower($finfo['extension']);
if(!in_array($ext , array('csv'))){
$this->set_flash_msg("Document formaat niet ondersteund", "danger");
}
else{
$file_path = $_FILES['file']['tmp_name'];
if(!empty($file_path)){
$request = $this->request;
$db = $this->GetModel();
$tablename = $this->tablename;
$options = array('table' => $tablename, 'fields' => '', 'delimiter' => ',', 'quote' => '"');
$data = $db->loadCsvData( $file_path , $options , false );
if($db->getLastError()){
$this->set_flash_msg($db->getLastError(), "danger");
}
else{
$this->set_flash_msg("Data imported successfully", "success");
}
}
else{
$this->set_flash_msg("Error uploading file", "danger");
}
}
}
else{
$this->set_flash_msg("No file selected for upload", "warning");
}
$this->redirect("aflossingen");
}
This is my code. Nothing happens:
function import_data(){
if(isset($_POST["importcsv"])){
$file = $_FILES["csv_file"]["tmp_name"];
$handle = fopen($file,"r");
while ($row = fgetcsv($handle)) {
$id = $row[0];
$Aflossingdatum = $row[2];
$Aflossingsbedrag = $row[3];
$Afgelost = $row[4];
$Saldo = $row[5];
$sql = "UPDATE aflossingen SET Aflossingdatum = Aflossingdatum,Afgelost = Afgelost, Saldo = Saldo WHERE AflossingID = AflossingID";
$update_data_stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($update_data_stmt, $sql)){
die("Something went wrong with the upload. " . mysqli_error($connection));
} else {
mysqli_stmt_bind_param($update_data_stmt, "ss", $Aflossingdatum, $id, $Aflossingsbedrag, $Afgelost, $Saldo);
mysqli_stmt_execute($update_data_stmt);
if ($id == "AflossingID" && $Aflossingdatum == "Aflossingdatum"){
echo "";
} else {
echo "Lead <b>{$id}</b>'s response was updated to <b>{$Aflossingdatum}</b>.</p>";
}
}
}
}
$this->redirect("aflossingen");
}
You're not creating the prepared statement correctly. It needs to have ? placeholders where the variables will be substituted.
And you need to have as many characters in the type string argument to mysqli_stmt_bind_param() as you have variables. And the variables have to be in the same order as in the query, so $id must be last.
You don't need to prepare the statement and bind parameters each time through the loop. Just prepare it once, and bind the parameters to reference variables that will be updated during the loop.
You were missing Aflossingsbedrag from your UPDATE query, I added it back.
Instead of checking whether $id == 'AflossingID' to skip the header row, I simply read the first line of the file before going into the loop that calls fgetcsv(). If you prefer to do it by checking the column value (in case there's no header) you should do it before executing the query, and skip the update (you can use continue; to go to the next iteration of the loop)
function import_data(){
if(isset($_POST["importcsv"])){
$file = $_FILES["csv_file"]["tmp_name"];
$handle = fopen($file,"r");
$sql = "UPDATE aflossingen SET Aflossingdatum = ?, Aflossingsbedrag = ?, Afgelost = ?, Saldo = ? WHERE AflossingID = ?";
$update_data_stmt = mysqli_stmt_init($connection);
mysqli_stmt_bind_param($update_data_stmt, "sssss", $Aflossingdatum, $Aflossingsbedrag, $Afgelost, $Saldo, $id);
if (!mysqli_stmt_prepare($update_data_stmt, $sql)){
die("Something went wrong with the upload. " . mysqli_error($connection));
}
fgets($handle); // Skip header row
while ($row = fgetcsv($handle)) {
$id = $row[0];
$Aflossingdatum = $row[2];
$Aflossingsbedrag = $row[3];
$Afgelost = $row[4];
$Saldo = $row[5];
if (mysqli_stmt_execute($update_data_stmt)) {
echo "Lead <b>{$id}</b>'s response was updated to <b>{$Aflossingdatum}</b>.</p>";
} else {
echo "Something went wrong when updating $id. " . mysqli_stmt_error($update_data_stmt);
}
}
}
}

odbc_num_rows is not work

$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

PHP Update statement not working because of the number of parameters

I have some php code for an app that I built. I have an sql statement that updates on duplicate key that is not working. It seems to have something to do with the number of parameters in the update part of the call. Please let me know if you have an idea on what the problem might be.
<?php
//database connection variables
$hostname = "";
$username = "";
$password = "";
$dbName = "";
//files to capture json
$incomingJson = 'json.txt';
// initialize the string with a blank value
$string = "";
function insertNewRowIntoStatistics($db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate) {
$sqlInsertNewRow = <<<'EOT'
INSERT INTO Statistics(
charactersName,
highscoreFeet,
charactersFitnessLevel,
worstJump,
totalTrainingTime,
startingDate
) VALUES ( ?, ?, ?, ?, ?, ? )
ON DUPLICATE KEY UPDATE
highscoreFeet = VALUES(highscoreFeet),
charactersFitnessLevel = VALUES(charactersFitnessLevel),
worstJump = VALUES(worstJump),
totalTrainingTime = VALUES(totalTrainingTime)
EOT;
$stmt1 = $db->prepare($sqlInsertNewRow);
$stmt1->bind_param("siiiis",
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate);
$stmt1->execute();
$stmt1->bind_result($result);
$stmt1->fetch();
$stmt1->close();
if(!$result){
trigger_error("Error inserting into Statistics, $result", E_USER_ERROR);
}
}
//Create function for deleting rows that have been in queuedRows for more then 5 minutes.
function deleteExpiredRowsInQueuedRows($db) {
$sqlDeleteQueuedRow = "DELETE FROM queuedRows WHERE timeOfCreation < ?";
$stmt4 = $db->prepare($sqlDeleteQueuedRow);
$stmt4->bind_param($stmt4, 'i', DateAdd(mi, -5, GetDate()));
$stmt4->execute();
$stmt4->bind_result($result);
$stmt4->fetch();
$stmt4->close();
// catch any errors
if(!$result){
trigger_error("Error deleting from queuedRows, $result", E_USER_ERROR);
}
}
//Create function for inserting rows that have been searched for into queued rows.
function insertRowInQueuedRows($db, $charactersName) {
$sqlInsertRowInQueuedRows = "Insert INTO queuedRows(charactersName, highscoreFeet, charactersFitnessLevel, worstJump, totalTrainingTime, startingDate, timeOfCreation) SELECT (charactersName, highscoreFeet, charactersFitnessLevel, worstJump, totalTrainingTime, startingDate, timeOfCreation) FROM Statistics where charactersName = ?";
$stmt3 = $db->prepare($sqlInsertRowInQueuedRows);
$stmt3->bind_param(1, $charactersName);
$stmt3->execute();
$stmt3->bind_result($result);
$stmt3->fetch();
$stmt3->close();
if(!$result){
trigger_error("Error inserting into queuedRows, $result", E_USER_ERROR);
}
}
function handleLineOfData( $db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate ) {
if($startingDate != "1/1/1") {
//Insert or update a row in main table, Statistics.
insertNewRowIntoStatistics($db,
$rowName,
$charactersName,
$highscoreFeet,
$charactersFitnessLevel,
$worstJump,
$totalTrainingTime,
$startingDate);
} else {
//Search for the character name instead of adding it/delete expired rows.
insertRowInQueuedRows($db, $charactersName);
deleteExpiredRowsInQueuedRows($db);
}
}
//Connecting to your database
$mysqli = new mysqli($hostname, $username, $password, $dbName);
//If error occurs connection to database
if (mysqli_connect_error()) { trigger_error("Cannot connect", E_USER_ERROR); exit; }
//var_dump($_SERVER);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
var_dump( $_POST );
//capture incoming data
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$sig = $_POST["sig"];
if( isset($_POST['params']) ) {
$jsondata = $_POST["params"];
//Captures sent json to figure out what to send back
//file_put_contents($incomingJson,$jsondata);
//converts JSON to an array
$array = json_decode($jsondata, TRUE);
//formats the array to view it easier
$results = print_r($array,true);
//file_put_contents($fullArray, $results);
//gets the total number of objects in the array
$arrlength = count($array['Children']['1']['Properties']);
//loop through array node and get row values
for ($i=0; $i < $arrlength; $i++) {
// get row value
$value = $array['Children']['1']['Properties'][$i]['Value']."\n";
// convert delimited string to an array
$arrayPieces = explode("|", $value);
$rowName = $arrayPieces[0];
$charactersName = $arrayPieces[1];
$highscoreFeet = $arrayPieces[2];
$charactersFitnessLevel = $arrayPieces[3];
$worstJump = $arrayPieces[4];
$totalTrainingTime = $arrayPieces[5];
$startingDate = $arrayPieces[6];
handleLineOfData( $mysqli, $rowName, $charactersName,
$highscoreFeet, $charactersFitnessLevel,
$worstJump, $totalTrainingTime, $startingDate );
}
}
// report http success even if data wasn't found
//Tells application of success
echo '{"Status":"Success"}';
} // end of POST
// start GET data
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//var_dump( $_GET );
// initialize the JSON body variable
$jsonBody="";
//get table contents
$query = mysqli_query($mysqli, "SELECT * FROM queuedRows");
//construct an array to hold the data pulled down from mySQL
$rows = array();
// loop through the table and drop the data into the array
while($row = mysqli_fetch_assoc($query)) {
$rows[] = $row;
}
// get the number of rows in the array for the JSON return
$arrlength = count($rows);
// set while loop index
$i = 0;
//loop through array node and get row values
while ($i < $arrlength ) {
// tables we are capturing
$charactersName = $rows[$i]['charactersName'];
$highscoreFeet =$rows[$i]['highscoreFeet'];
$charactersFitnessLevel = $rows[$i]['charactersFitnessLevel'];
$worstJump = $rows[$i]['worstJump'];
$totalTrainingTime = $rows[$i]['totalTrainingTime'];
$startingDate = $rows[$i]['startingDate'];
// table row numbers. index starts at 0, increment it by 1 to get valid row numbers.
$tableRow = $i+1;
// construct the JSON return from data
$jsonString ='{"Name":"'.$tableRow.'","Value":"|'.$charactersName.'|'.$highscoreFeet.'|'.$charactersFitnessLevel.'|'.$worstJump.'|'.$totalTrainingTime.'|'.$startingDate.'|"},';
// append the JSON return with the new data
$jsonBody=$jsonBody.$jsonString;
// increase index and loop again if not at end of array.
$i++;
}
// construct the JSON response to send table back to app
// this is the header of the JSON return.
$jsonHeadher='{"Properties":[],"Name":"id946381_headers","Children":[{"Properties":[{"Name":"rowCount","Value":'.$arrlength.'},{"Name":"columnCount","Value":6},{"Name":"0-1-name","Value":"charactersName"},{"Name":"0-1-type","Value":1},{"Name":"0-2-name","Value":"highscoreFeet"},{"Name":"0-2-type","Value":2},{"Name":"0-3-name","Value":"charactersFitnessLevel"},{"Name":"0-3-type","Value":2},{"Name":"0-4-name","Value":"worstJump"},{"Name":"0-4-type","Value":2},{"Name":"0-5-name","Value":"totalTrainingTime"},{"Name":"0-5-type","Value":2},{"Name":"0-6-name","Value":"startingDate"},{"Name":"0-6-type","Value":1}],"Name":"id946381_headers","Children":[]},{"Properties":[';
// this is the footer of the JSON return.
$jsonFooter='],"Name":"id946381","Children":[]}]}';
// removes an extra comma that the loop above leaves behind
$jsonBody=rtrim($jsonBody, ",");
// constructing the full JSON return
$returnedJson=$jsonHeadher.$jsonBody.$jsonFooter;
// write the JSON data so the app can read it.
echo $returnedJson;
} // end of get
//Close out mysql
$mysqli->close();
?>

multiple row saving to DB table

I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}

How to solve cannot use string offset as an array error in PHP?

I want to add multiple data into table at once but my code gives an error saying 'cannot use string offset as an array'. I have attached my code. Can anyone help me to solve this?
$issuedate=$_POST['issuedate'];
$member=$_POST['member'];
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
$bno[2]['TitleNo'] = $_POST['bno2'];
$bno[3]['TitleNo'] = $_POST['bno4'];
$returndate = $_POST['returndate'];
for($i=0; $i<4; $i++)
{
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
}
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
You are probably assigning string to $bno variable thus it dynamically becomes of type string. More info here. Regarding the example you should
$bno = array();
Escape all your DB inputs (or even better, use prepared statements)
It makes more sense to put the if..else inside the for loop
Thus
$bno = array();
$mysqli_conn = mysqli_connect("localhost", "user", "password", "schema");
$issuedate = mysqli_real_escape_string($mysqli_conn, $_POST['issuedate']);
$member = mysqli_real_escape_string($mysqli_conn, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno4']);
$returndate = mysqli_real_escape_string($mysqli_conn, $_POST['returndate']);
for($i=0; $i<4; $i++)
{
$sql = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','".$member."','".$issuedate."','".$returndate."')");
if ($sql)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
}
You have set $bno as string in some previous code.
What you can do for a quick fix is:
change $bno to somehing else, for example $book
$book[0]['TitleNo'] = $_POST['bno'];
$book[1]['TitleNo'] = $_POST['bno1'];
//..
set $bno to a new array and then assign the values
$bno = array();
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
//...
Additional Notes
By the way it's better to escape somehow the values you enter in your DB. You can use mysqli_real_escape_string
Just assign do this for all the values:
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
Sources to read
http://php.net/manual/en/mysqli.real-escape-string.php
You should have a look att prepared statements and bind params. When you're doing the insert statements you select five columns and only inserts four values.
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
And as #jeroen mentioned, your code has sql-injection problems, read more about sql-injection here.
I've created and exampel using prepared statements and bind params. Note:
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
'sssss' are just for demo purpose, I assume dueDate and returndate columns are datetime something simular.
$DBServer = 'localhost';
$DBUser = 'root';
$DBPass = 'root';
$DBName = 'borrow';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$sql = ' INSERT INTO borrow (TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES (?,?,?,?,?)';
$TitleNo = $bno[0]['TitleNo'];
$member = 'MemberID';
$issuedate = 'issuedate';
$dueDate = 'dueDate';
$returndate = 'returndate';
/* Prepare statement */
$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
for( $i= 0; $i < count($bno); $i++){
/* Bind parameters. s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
/* Execute statement */
$stmt->execute();
}
if( $stmt->affected_rows > 0 ){
echo '<h4 class="message">Add New Book Copies!</h4>';
}
$stmt->close();
However im not sure if it's best practice to do a mass insert to db using a for-loop.
Initialising your array (ie, $bno was probably initialised to a string in your code which caused the error you are seeing), escaping the input and doing a single INSERT (rather than 4, where you only check the results of the last one):-
<?php
$bno = array();
$sql_array = array();
$issuedate = mysqli_real_escape_string($db, $_POST['issuedate']);
$member = mysqli_real_escape_string($db, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno4']);
$returndate = mysqli_real_escape_string($db, $_POST['returndate']);
foreach($bno AS $abno)
{
$sql_array = "('".$bno['TitleNo']."','$member','$issuedate','$returndate')"
}
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate)
VALUES ".implode(', ', $sql_array));
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies!</h4>';
// echo $test;
}
else
{
echo 'Fail.';
}
This does suggest that the database could be further normalised, as you have multiple rows being inserted that are identical except for one value.

Categories