简体   繁体   中英

inserting serialized array in mysql

I am trying to insert a serialized array into mysql without column names, is it possible?

I plan to use this in a function with a dynamic number of textboxes so I will just call the function and pass the tablename and insert into the database in order.

Here is the code I currently have:

<form action = "" method = "POST">

    Username: <input required type = "text" name = "register[]" / ><br />
    Password: <input required type = "text" name = "register[]" / ><br />
    Usertype: <input required type = "text" name = "register[]"  / ><br />
    Status:   <input required type = "text" name = "register[]" / ><br />
    <input  type = "submit" name = "add" value = "add" / >

</form>

if(isset($_POST['add']))
{

    $reg = serialize($_POST['register']); //takes the data from a post operation...
    $register = mysql_real_escape_string($reg);
    $query = mysql_query("INSERT INTO user VALUES('$register')");    
}

working queries:

$query = mysql_query("INSERT INTO users (username,password,usertype,status) VALUES('$register','2','3','4')"); 

output:

a:4:{i:0;s:1:"1";i:1;s:1:"1";i:2;s:1:"1";i:3;s:1:"1";} 2 3 4

You can't use PHP serialize() to conveniently insert multiple data into multiple MySQL fields. serialze() transforms complex php's type into single string. One single string. You may use it to store an array with all these values into one text field, but that is not what you wanted.

mysql_query("INSERT INTO users (username,password,usertype,status)
 VALUES('".mysql_real_escape_query($_POST['register'][0])."',
 '".mysql_real_escape_query($_POST['register'][1])."',
 '".mysql_real_escape_query($_POST['register'][2])."',
 '".mysql_real_escape_query($_POST['register'][3])."' )");

Alternatively using PDO:

$dbh = new PDO('mysql:dbname=test;host=localhost','root','pass');
$sth = $dbh->prepare('INSERT INTO users (username,password,usertype,status)
  VALUES(?,?,?,?)');
$sth->execute($_POST['register']);

您忘了包含表的字段名

$query = mysql_query("INSERT INTO user(username,password,usertype,status) VALUES('$register')"); 

i madeit work but using a different method i used implode but its the same

$register = "'" . implode("','", $_POST['register']) . "'";
$query = mysql_query("INSERT INTO users VALUES(null,$register)"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM