Using transactions in PHP and MySQL - php

I'm a learner of PHP. This commit and rollback process does the task at each line. How can I commit and rollback all at once?
<?php
$con = mysql_connect('localhost','user', 'abcdefg');
if(!con)
{
echo "Can't connect to db.";
}else {
mysql_select_db('test');
}
if(!file_exits('test.csv')
{
echo "Can't find the file.";
}
$ar_1 = file('test.csv', FILE_IGNORE_NEW_LINES);
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === true)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}else {
//Rollback
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
}
}
mysql_close($con);
?>

you need to commit out of the loop, i used $bool to see if there somewhere the $result isn't true
it will look something like :
edit:
breaking from the loop when something is wrong as you don't need to continue looping to other elements.
$bool = 1;
foreach ($ar_1 as $ar1)
{
$test = explode(",", $ar1);
$sql = "SELECT * FROM DB WHERE CD = '$test[0]'";
$result = mysql_query_($sql);
$sql = "INSERT INTO DB(CODE) VALUES ('$test[0]');";
$result = mysql_query($sql);
if($result === false)
{
//Rollback
$bool = 0;
$sql = "rollback";
mysql_query($sql);
echo "Rollback";
break;
}
}
if($bool == 1)
{
//Commit
$sql = "commit";
mysql_query($sql);
echo "Committed";
}
mysql_close($con);

Related

How to get value from mssql DB in PHP

Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}

multiple data queries php ajax mysql not working

<?php
$link = mysql_connect("localhost:8889", "root", "root", "Testdata");
if(!link) {echo "Database connexion not possible"; exit;}
$id = $_GET('testeId');
$jsonData = [];
The first query is working:
$jsonData['table1'] = [];
$sql = "SELECT * FROM registerData WHERE testeId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table1'][] = $row;
}
}
else {
$jsonData['table1'][] = "Error 1";
}
This second query is not working:
$jsonData['table2'] = [];
$sql = "SELECT * FROM factsData WHERE factsId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table2'][] = $row;
}
}
else {
$jsonData['table2'][] = "Error 2";
}
mysqli_free_result($result);
echo json_encode($jsonData);
The jsonData string only includes the 1st query:
mysqli_close($link);
The responseText of the ajax request only has data from "table1" array

How to query the database before insertion

I'm trying to query the data base to check whether the marks for current schedule is already updated in the data base before inserting, My code as follows:
<?php
include 'config.php';
if(isset($_POST['submit'])){
$schedule = $_POST['hischedule'];
$array = $_POST['marks'];
//Qry to check Duplicate values Againest Database
$marksupdqry = "select distinct scheduleName from marks";
$mks = mysqli_query($link, $marksupdqry);
while($mksresult = mysqli_fetch_array($mks))
foreach($mksresult as $sdlnme)
if($sdlnme = $schedule){
echo "<script> alert('Marks for this schedule already exist in db');</script>";
echo "<script> window.location.href='marks.php';</script>";
}else{
foreach ($array as $reg_num=>$score)
{
$ins = "INSERT INTO marks (sl_no, scheduleName, obtainedMarks) VALUES ('$reg_num', '$schedule', '$score')";
$res = mysqli_query($link, $ins);
if($res){
//echo "Success";
$Message = urlencode("Marks updated successfully ");
header("Location:marks.php?Message=".$Message);
die;
}
}
}
}
?>
My problem is I'm unable to execute both if and else part of my code.
Modify your code like bellow:
<?php
include 'config.php';
if(isset($_POST['submit'])){
$schedule = $_POST['hischedule'];
$array = $_POST['marks'];
$marksupdqry = "select distinct scheduleName from marks";
$mks = mysqli_query($link, $marksupdqry);
while($mksresult = mysqli_fetch_array($mks)){
foreach($mksresult as $sdlnme){
if($sdlnme == $schedule){
echo "<script> alert('Marks for this schedule already exist in db');</script>";
echo "<script> window.location.href='marks.php';</script>";
}else{
foreach ($array as $reg_num=>$score)
{
$ins = "INSERT INTO marks (sl_no, scheduleName, obtainedMarks) VALUES ('$reg_num', '$schedule', '$score')";
$res = mysqli_query($link, $ins);
if($res){
//echo "Success";
$Message = urlencode("Marks updated successfully ");
header("Location:marks.php?Message=".$Message);
die;
}
}
}
}
}
}
?>

IF/ELSE condition in sql and php

I'm inserting into my database id and hours, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result. The if/else statement must check first if hours (a column in the table) value is empty, if so then perform sql insert, else perform sql update. Any help please?
if (isset($_POST['submit'])) {
$hours = $_POST['Hours'];
$selectid = $_POST['SelectID'];
$sql1 = "INSERT INTO `editedworkhours` (`id`,`H`) VALUES('$selectid','$hours')";
$getResult = mysql_query($sql1);
if (mysql_affected_rows() > 0) {
} else {
}
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET H ='" . $_GET["hours"] . "' WHERE IDNumber='" . $_GET["selectid"] . "'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
} else {
}
}
echo $menu;
Try this
<?php
if(isset($_POST['submit']))
{
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
$sql1="SELECT * FROM editedworkhours WHERE AFNumber='$selectaf' and AddedWH ='$addedhours'";
$getResult = mysql_query($sql1);
$count = count($getResult);
if(!empty($count) || $count==1)
{
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET AddedWH ='$addedhours' WHERE AFNumber='$selectaf'";
$result2 = mysql_query($sql2);
if (isset($result2))
{
//Data inserted
}
else
{
//Insert Failed
echo '<script>swal("Error", "Something went wrong error");</script>';
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}
else
{
$sql3 = "INSERT INTO editedworkhours (AFNumber,AddedWH) VALUES('$selectaf','$addedhours')";
$Result = mysql_query($sql3);
if(isset($Result))
{
echo 'Success';
}
else
{
echo 'Failed';
}
}
}
echo $menu;

Cant base64 decode from mysqli

I'm currently trying to echo information from my SQL database which I had to encode in order for it to efficiently write into the table; now when I try to echo the information, WHILE decoding it, the page displays nothing, I'm not entirely sure what I'm doing wrong at this point.
<?php
$type = $_SESSION['SESS_ACC_TYPE'];
$login = $_SESSION['SESS_LOGIN_NAME'];
$log = base64_decode(''.$row['log'].'');
if ($type == '2') {
$qry = "SELECT log FROM logs ";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)){
echo ''.$log.'';
}
}
if ($type == '1') {
$qry = "SELECT log FROM logs WHERE login = '.$login.'";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)){
echo ''.$log.'';
}
} else {
//do nothing
}
?>
There are many errors with your code:
I fixed them.
$type = $_SESSION['SESS_ACC_TYPE'];
$login = $_SESSION['SESS_LOGIN_NAME'];
if ($type == '2') {
$qry = "SELECT `log` FROM `logs`;";
}
if ($type == '1') {
$qry = "SELECT `log` FROM `logs` WHERE `login` = '" . $login . "';";
}
$result = mysqli_query($GLOBALS["___mysqli_ston"], $qry);
while($row = mysqli_fetch_assoc($result)) {
echo base64_decode($row['log']);
}
since mysql 5.6.1 there are mysql base64 decode/encode functions
select FROM_BASE64('....') ...
select TO_BASE64('....') ...
http://base64decode.net/mysql-from-base64

Categories