SQLSRV bind param thats in mysql - php

I'm trying to convert this mysql code to work using sqlsrv
$planeId = $_GET["pid"];
$conn = OpenCon();
$sql = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
$stmnt = $conn->prepare($sql);
$stmnt->bind_param("s", $planeId);
$stmnt->bind_result($id, $pid, $fullname, $tat, $date, $engine1, $engine2, $engine3, $engine4);
$stmnt->execute();
$theRows = Array();
while ( $stmnt->fetch() )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
$stmnt->close();
echo json_encode($theRows);
CloseCon($conn);
This I what I've done so far but I'm missing the bind-param function not sure how to implement that. Because the output keeps coming out like this
[{"id":"","pid":"","fullname":null,"tat":null,"date":null,"engine1":null,"engine2":null,"engine3":null,"engine4":null}]
Even though I know there's an entry in Microsoft DB
$planeId = $_GET["pid"];
$theRows = Array();
$conn = OpenCon();
$query = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
//$stmnt = $conn->prepare($query);
$stmnt = sqlsrv_prepare($conn, $query, array(&$planeId));
if (sqlsrv_execute($stmnt) === false){
die( print_r( sqlsrv_errors(), true));
}
else{
while ( sqlsrv_fetch($stmnt) )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
echo json_encode($theRows);
}
CloseCon($conn);

Related

getting values for PHP array

I have below query in php and want to extract the values from the array and want to use them in a function withing foreach loop. But the values i am getting from the array are wrong. I can not figure out what is wrong here as i am newbie to PHP.
$sql="SELECT * FROM `mlm_pending_transactions` WHERE member_id = $_SESSION[member_id] and cycle=$cycle_number and credited=0 and order_type='upgrade_commission_cash'";
$result=mysql_query($sql);
while($data_set = mysql_fetch_array($result))
{
foreach($data_set as $cash_pendings)
{
echo $cash_pendings["member_id"]."</br>";
echo $cash_pendings['tran_amount']."</br>";
echo $cash_pendings['tran_particulars']."</br>";
echo $cash_pendings['id'];
}
}
All you need are the values from the array returned by mysql_fetch_array()
$sql="SELECT * FROM `mlm_pending_transactions` WHERE member_id = $_SESSION[member_id] and cycle=$cycle_number and credited=0 and order_type='upgrade_commission_cash'";
$result=mysql_query($sql);
while($data_set = mysql_fetch_array($result))
{
echo $data_set["member_id"]."</br>";
echo $data_set['tran_amount']."</br>";
echo $data_set['tran_particulars']."</br>";
echo $data_set['id'];
}
Note if the field names are wrong (they are case sensitive) then the values will not be returned.
You could use print_r($data_set) to check on the field names returned if you are not sure.
EDIT - Changes for your actual error.
Absolute minimum. Note not tested so maybe some typos.
<?php
$sql="SELECT *
FROM `mlm_pending_transactions`
WHERE member_id = $_SESSION[member_id]
AND cycle = $cycle_number
AND credited = 0
AND order_type = 'upgrade_commission_cash'";
$result = mysql_query($sql);
while($data_set = mysql_fetch_array($result))
{
echo $data_set["member_id"]."</br>";
echo $data_set['tran_amount']."</br>";
echo $data_set['tran_particulars']."</br>";
echo $data_set['id'];
$date = date("m/d/Y");
$time = strtotime("now");
$add_cash = $affiliate->add_fin_tran($data_set["member_id"],
$data_set["tran_amount"],
0,
$data_set["tran_particulars"],
"upgrade_commision_cash",
1);
$sql2 = "UPDATE mlm_pending_transactions
SET credit = 1,
credited_date = '$date',
credited_time = '$time'
WHERE id = ".$data_set["id"];
$result2 = mysql_query($sql2);
}
?>
However, as others have said you are using the deprecated mysql_* function. Further you have zero protection from SQL injection.
You should use one of the newer methods of accessing the databases. Generally either the mysqli_* functions or the pdo based functions. Note to use these you will also need to switch the function to connect to the database (to the matching ones).
For example, using mysqli_ functions (you can also use these using object orientated syntax):-
<?php
$sql = "SELECT *
FROM `mlm_pending_transactions`
WHERE member_id = ?
AND cycle = ?
AND credited = ?
AND order_type = ?";
$statement = mysqli_prepare($db_connection, $sql);
mysqli_stmt_bind_param($statement, 'iiis', $_SESSION['member_id'], $cycle_number, 0, 'upgrade_commission_cash');
mysqli_execute($statement);
$result = mysqli_get_result($statement);
while($data_set = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $data_set["member_id"]."</br>";
echo $data_set['tran_amount']."</br>";
echo $data_set['tran_particulars']."</br>";
echo $data_set['id'];
$date = date("m/d/Y");
$time = strtotime("now");
$add_cash = $affiliate->add_fin_tran($data_set["member_id"],
$data_set["tran_amount"],
0,
$data_set["tran_particulars"],
"upgrade_commision_cash",
1);
$sql2 = "UPDATE mlm_pending_transactions
SET credit = ?,
credited_date = ?,
credited_time = ?
WHERE id = ?";
$statement2 = mysqli_prepare($db_connection, $sql2);
mysqli_stmt_bind_param($statement2, 'issi', 1, $date, $time, $data_set["id"]);
$result2 = mysqli_execute($statement2);
}
?>
Using the object orientated syntax:-
<?php
$sql = "SELECT *
FROM `mlm_pending_transactions`
WHERE member_id = ?
AND cycle = ?
AND credited = ?
AND order_type = ?";
$statement = $db_connection->prepare($sql);
$statement->bind_param('iiis', $_SESSION['member_id'], $cycle_number, 0, 'upgrade_commission_cash');
$statement->execute();
$result = $statement->get_result();
while($data_set = $result->fetch_array(MYSQLI_ASSOC))
{
echo $data_set["member_id"]."</br>";
echo $data_set['tran_amount']."</br>";
echo $data_set['tran_particulars']."</br>";
echo $data_set['id'];
$date = date("m/d/Y");
$time = strtotime("now");
$add_cash = $affiliate->add_fin_tran($data_set["member_id"],
$data_set["tran_amount"],
0,
$data_set["tran_particulars"],
"upgrade_commision_cash",
1);
$sql2 = "UPDATE mlm_pending_transactions
SET credit = ?,
credited_date = ?,
credited_time = ?
WHERE id = ?";
$statement2 = $db_connection->mysqli_prepare($sql2);
$statement2->bind_param('issi', 1, $date, $time, $data_set["id"]);
$result2 = $statement2->execute();
}
?>

Why does php mysqli_prepare select query return null?

I'm using php to get data from database, but i have a problem.
First of all, It is php file which gets data from database.
<?php
$con = mysqli_connect(mydatabase_address, myid, password);
$userLocation = $_POST["userLocation"];
$stmt = mysqli_prepare($con, "SELECT * FROM neighborTable WHERE postLocation = ?");
mysqli_stmt_bind_param($stmt, "s", $userLocation);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $ID, $postWriter, $postContent, $postDate, $postPic, $postLike, $postComments, $postLocation, $profilePic, $postGatherDate, $postGatherLocation, $postGatherTime);
$response = array();
while($row = mysqli_stmt_fetch($stmt)) {
$row_array['ID'] = $ID;
$row_array['postWriter'] = $postWriter;
$row_array['postContent'] = $postContent;
$row_array['postDate'] = $postDate;
$row_array['postPic'] = $postPic;
$row_array['postLike'] = $postLike;
$row_array['postComments'] = $postComments;
$row_array['postLocation'] = $postLocation;
$row_array['profilePic'] = $profilePic;
$row_array['postGatherDate'] = $postGatherDate;
$row_array['postGatherLocation'] = $postGatherLocation;
$row_array['postGatherTime'] = $postGatherTime;
array_push($response, $row_array);
}
echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
However, it returns like below. It has correct number of data, but its values are all null. How can i solve this problem?
{"response":[{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null},{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null},{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null}]}

Error in MySQLi insert_id

I'm trying to get the registry id inserted in the database using MySQLi insert_id but it is giving error.
I already researched the web but found nothing that solved this problem.
Where am I going wrong?
<?php
date_default_timezone_set('America/Sao_Paulo');
$data = date('d-m-Y');
$hora = date('H:i:s');
$id_motorista = $_POST["id_motorista"];
$km = $_POST["km"];
$valor = $_POST["valor"];
$placa = $_POST["placa"];
$posto = $_POST["posto"];
$litros = $_POST["litros"];
$photo_user_origem = $_FILES["photo_user"]["tmp_name"];
$photo_user_destino = "photos/".md5(time()).".png";
$conn = new mysqli("localhost", "root", "", "banco");
$sql = "INSERT INTO abastecimentos (dia, km, posto, litros, placa, valor, id_motorista) VALUES ('$data','$km','$posto','$litros','$placa','$valor','$id_motorista')";
$stm = $conn->prepare($sql);
//ERROR SHOULD BE THERE STARTED HERE
if ($stm->execute()){
$id_bastecimento = $conn->insert_id;
$stm->close();
if (move_uploaded_file($photo_user_origem, $photo_user_destino)){
$sql_update_photo = 'UPDATE abastecimentos SET photo_usuario = ? WHERE id_bastecimento = ?';
$stm = $conn->prepare($sql_update_photo);
$stm->bind_param("si", $photo_user_destino, $id_bastecimento);
$stm->execute();
}
$retorno = array("retorno" => "YES");
} else {
$retorno = array("retorno" => "NO");
}
echo json_encode($retorno);
$stm->close();
$conn->close();
?>

PHP MySql PDO Multiple insert doesn't work

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

Using recurssion in deleting parent and child relationship in mysql table

I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent

Categories