Domanda

I have a page that contains data from the database. That data is suposed to be altered by the user and then insert it into the database.

I have an input type hidden - <input type='hidden' name='data[]'>".$ppdata
This Sends the $ppdata variable to another page (The form is unecessary to show).

I Receive the Array in the next page like this:

$ippdata = 0;
foreach ($_POST["data"] as $dat){
   $dataarray[$ippdata] = $dat;
   $ippdata++;
}

Then i try to insert the data:

$data = count($dataarray);

for($contador = 0; $contador < $data; $contador++){
   $str[] = "('{$dataarray[$contador]}' )";
 }    
$s = implode(',',$str);
$sql = mysql_query("INSERT INTO pp (data) VALUES $s;");

This inserts a blank field in the database. 4 - because that user only had 4 records.

NOTE: The $ppdata variable is gotten from the database, and it is edited just by clicking on the data throught JQuery. It is impossible to insert MORE records with the first page. This is passing an array with 4 positions. Each positions contains a record from the database. (4 records because that's the data that corresponds to an user. A user can have more records).

Thanks !

È stato utile?

Soluzione

i would try something like this.

$data = count($dataarray);
$str = "";

for($contador = 0; $contador < $data; $contador++){
   $str.= "('{$dataarray[$contador]}' )";
   if($data != $contador){
    $str.= ", ";
   }
 }    
$query = "INSERT INTO pp (data) VALUES ".$str;
$sql = mysql_query($query);

or you can try using something like this.

$mysqli = new mysqli($host, $username, $password, $db_name);

/* check connection */  
if (mysqli_connect_errno()) {       
    printf("Connect failed: %s\n", mysqli_connect_error());         
    exit();     
}

$stmt = $mysqli->prepare("INSERT INTO pp (data) VALUES (?);");
    for($contador = 0; $contador < $data; $contador++){
       $stmt->bind_param('s', $dataarray[$contador]);
       $stmt->execute();
     }      
$stmt->close(); 

Altri suggerimenti

I think you are trying to save a JSON string or something.

Shorter method:

if(!empty($_POST["data"])) {
    $data = json_encode($_POST["data"]);
}

$query = mysql_query("INSERT INTO pp (data) VALUES '".$data."'");

This is the shorter way.

You can get this data by decoding data field like this.

$data = json_decode($db_record, true); //true for returning array.

If you really want to make it in your own way than even so there is a shorter way.

if(!empty($_POST["data"])) {
    $str = '';
    foreach($_POST["data"] as $key => $data) {
       $str .= '{'.$data.'}'. (key($_POST["data"]) != $key ? ',' : '');
    }
}

$query = mysql_query("INSERT INTO pp (data) VALUES '".$str."'");

You're not posting any value in your hidden input(s):

<input type="hidden" name="data[]" value="the value to post" />
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top