php insert into mysql from array with mysqli -
php insert into mysql from array with mysqli -
hi want insert info parsed json table, when it, doesn't work, returns 0 rows, missing? i'm new yet "mysqli".. have more 25000 rows insert table. thx
$mysqli = mysqli_connect('localhost', 'root', '', ''); $alldata = $datasource->getalldata(); foreach ($alldata $key => $value) { $query = 'insert `table`(`data_id`, `name`) values (' . $value['data_id'] . ', ' . $value['name'] . ')'; $result = mysqli_query($mysqli, $query); } it works now, inserted object data, code made thx replies this:
$mysqli = mysqli_connect('localhost', 'root', '', '') or die(mysqli_connect_error()); if (!$mysqli) { die('could not connect: ' . mysqli_error()); } $alldata = $datasource->getalldata();
foreach ($alldata $key => $value) { $query = mysqli_prepare($mysqli, "insert `table`(`data_id`, `name`) values (?, ?)"); mysqli_stmt_bind_param($query, 'is', $value['data_id'], $value['name']); mysqli_stmt_execute($query); mysqli_stmt_close($query); } hope ok here, i'm new in mysqli , need lot of practice programming
seems should set single quotes around info values. adding mysqli_error check mysqli_query line can see happening:
$alldata = $datasource->getalldata(); foreach ($alldata $key => $value) { $query = "insert `table`(`data_id`, `name`) values ('" . $value['data_id'] . "', '" . $value['name'] . "')"; $result = mysqli_query($mysqli, $query) or die(mysqli_error()); } or improve yet, utilize mysqli_stmt_bind_param this. allow mysqli deal whole query info structuring instead of having worry single quote placement. also, added check mysqli_connect_error on mysqli_connect line:
// connecting, selecting database $mysqli = mysqli_connect('localhost', 'root', '', '') or die(mysqli_connect_error()); $alldata = $datasource->getalldata(); foreach ($alldata $key => $value) { // set query. $query = "insert `table`(`data_id`, `name`) values (?, ?)"; // bind params. // mysqli_stmt_bind_param($query, 'ss', $value['data_id'], $value['name']); mysqli_stmt_bind_param($query, 'is', $value['data_id'], $value['name']); // run query. $result = mysqli_query($mysqli, $query) or die(mysqli_error()); } note have commented line mysqli_stmt_bind_param since it’s not clear me if $value['data_id'] number or string. mysqli_stmt_bind_param($query, 'is',… means first value integer (i) , next value string (s). sense free adjust best fit actual info types.
php mysql sql mysqli
Comments
Post a Comment