Previous question:
I'd like this new question reviewed.
<?php
$mysqli = new mysqli('localhost','root','','yaztor');
if($mysqli->connect_errno >0){
die( "problem with the connection");
}
function fetchTableFieldCount($mysqli , $databaseName , $tableName ) {
$sql = "SELECT COUNT(`COLUMN_NAME`) AS FieldCount FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName' AND `TABLE_NAME`= '$tableName' ";
if ( ! ( $stmt = $mysqli->prepare($sql) ) ) {
die("There is an error with mysql preparation statement".$mysqli->error);
}
if ( ! $stmt->execute() ) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$res = $stmt->get_result();
if ( $row = $res->fetch_array() ) {
return $row['FieldCount'];
}
return 0;
}
function fetchTableFieldName($mysqli , $databaseName , $tableName ) {
$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName' AND `TABLE_NAME`= '$tableName' ";
if ( ! ( $stmt = $mysqli->prepare($sql) ) ) {
die("There is an error with mysql preparation statement".$mysqli->error);
}
if ( ! $stmt->execute() ) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$res = $stmt->get_result();
while( $row = $res->fetch_array() ) {
$array []= $row['COLUMN_NAME'];
}
return $array;
return 0;
}
function updateDataIntoTable($mysqli, $tableName, $databaseName, $array ,$idFeildName , $idFeildValue) {
if( ! $tableCoulmnsNames = fetchTableFieldName($mysqli , $databaseName , $tableName ) ){
die("Error Fetching Table Information");
}
$tableColumnsCount = count($tableCoulmnsNames);
$dataArrayCount = count($array);
if ( $tableColumnsCount != $dataArrayCount ) {
die("Data array does not match table columns count");
}
if ( 0 == $dataArrayCount ) {
return;
}
array_push($array,$idFeildValue);
for ( $i = 0; $i < sizeof($array); $i++ ) {
$string = gettype($array[$i]);
//taking the first letter; example: string = s, integer = i
$a_param_type[] = $string[0];
}
for($i=0;$i<$tableColumnsCount;$i++){
$tableCoulmnsNames[$i] = "`" . $tableCoulmnsNames[$i] ."`";
}
$sql = " UPDATE `$databaseName`.`$tableName` SET ";
$sql .= implode($tableCoulmnsNames , ' = ? , ' );
$sql .= ' = ? ';
$sql .=" WHERE `$tableName`.`$idFeildName` = ? ";
echo $sql;
if ( ! $stmt = $mysqli->prepare($sql) ) {
die("error in preparation " . $mysqli->error);
}
//puting data element type
array_unshift($array, implode($a_param_type));
//refrensing values
for($i=0;$i<sizeof($array) ;$i++){
$array[$i] = & $array[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $array);
if ( ! $stmt->execute() ) {
die("Error in executing the query: " . $mysqli->error);
}
return 1;
}
$array = array(10, 5 ,"name", "desc", "text", "12-1-2014 01:00", "1");
updateDataIntoTable($mysqli, "table", "database", $array ,"idFeildname" , $idFeildValue)
?>