Error trying to run a multiqyery - php

Sorry if its a little mistake. i was using first time multi query. error 1 and error 2 both codes are same except single colon('') added in error 2 insert row. if i echo from inside the the for loop shows everything fine. some time success but not inserted in data base. Thank You in advance.
Error 1: Error :You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'INSERT INTO student_attendance (attendance_date,
attendance_class_id, attendance' at line 1
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = '';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ) ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));
Error 2:You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''attendance_date', 'attendance_class_id',
'attendance_section_id', 'attendance_s' at line 1
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance ('attendance_date', 'attendance_class_id', 'attendance_section_id', 'attendance_student_id', 'attendance_present_absent' ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ) ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));

There are two mistakes. First is, in your for cycle you have to add ; after each INSERT string. Second, if you wanna use multiple insert, you should write INSERT part string before for cycle and then just add rows with values, there is , separator used.
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = '';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ); ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));
OR
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = 'INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) VALUES ';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= ($count>0?",":"") . "('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' )";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$query .= ";"
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));

Related

Change SQL Query to a prepared statement with condition

I'm trying to change this query to a query with prepared statement, but I have some problem because of conditions.
This is my basic query :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery='" . $idQuery . "'".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$result = mysqli_query($link,$sql) or die("Query (- $sql -) failed");
$count = mysqli_num_rows($result);
}
I changed it to this :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =?".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$stmt->bind_param('i', $idQuery);
$result = $stmt->execute() or die("Query (- $sql -) failed");
$result = $stmt->get_result();
$count = mysqli_num_rows($result);
}
but I don't know how can I change conditions($req_boutique,$req_agence) to prepared statement?
You can replace the inlined variables in your $req_boutique and $req_agence conditions with placeholders, and then conditionally bind values to them:
if($Boutique!=null){
$req_boutique = " AND C.idUser = ? ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = ? ";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =? ".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$types = 'i';
$vars = [$idQuery];
if ($Boutique != null) {
$types .= 's';
$vars[] = $Boutique;
}
if ($agency!= null) {
$types .= 's';
$vars[] = $agency;
}
$stmt->bind_param($types, ...$vars);

Transaction to Insert errors

I have read lots of questions tried lots of different ways to no success.
I am trying to insert into multiple tables.
I have a transaction, but it is throwing the error:
Warning: mysqli_query(): Empty query on the lines
starting:
if ($result).
I think I am missing something simple. This is really getting to me I must have spent a week trying to sort this out.
My tables are all innodb, all the column data type match.
I can do the individual insertions but not the multiple insertions.
<?php
$jid = $_REQUEST['JID'];
$CLx = $_REQUEST['CL'];
$CL = str_replace("'", "\'", $CLx);
$ADx = $_REQUEST['AD'];
$AD = str_replace("'", "\'", $ADx);
$DT = $_REQUEST['DT'];
$SS1 = $_REQUEST['SS1'];
$SS2 = $_REQUEST['SS2'];
$SS3 = $_REQUEST['SS3'];
$SVFNx = $_REQUEST['SVFN'];
$SVFN = str_replace("'", "\'", $SVFNx);
$CS = $_REQUEST['CS'];
$OFTC = $_REQUEST['OFTC'];
$SV = $_REQUEST['SV'];
$dbConnection = mysqli_connect ('10.169.999.999', 'boiw', 'Tx', 'bw1_pp');
mysqli_autocommit($dbConnection, false);
$flag =true;
$squery1 = "INSERT INTO `awg` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SS2`,`SS3`,`SVFN`,`CS) VALUES ($jid,$CL,$AD,$DT,$SS1,$SS2,$SS3,$SVFN,$CS)";
$squery2 = "INSERT INTO `cae` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SS2`,`SS3`,`SVFN`) VALUES ($jid,$CL,$AD,$DT,$SS1,$SS2,$SS3,$SVFN)";
$squery3 = "INSERT INTO `calc` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SS2`,`SS3`,`SVFN`) VALUES ($jid,$CL,$AD,$DT,$SS1,$SS2,$SS3,$SVFN)";
$squery4 = "INSERT INTO `costings` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SS2`,`SS3`,`SVFN`) VALUES ($jid,$CL,$AD,$DT,$SS1,$SS2,$SS3,$SVFN,$CS)";
$squery5 = "INSERT INTO `hazzard` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SVFN`,`CS`) VALUES ($jid,$CL,$AD,$DT,$SS1,$SVFN,$CS)";
$squery6 = "INSERT INTO `spay` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SS2`,`SS3`,`SVFN`,`surveyor`) VALUES ($jid,$CL,$AD,$DT,$SS1,$SS2,$SS3,$SVFN,$SV)";
$squery7 = "INSERT INTO `spix` (`JID`,`CL`,`AD`,`DT`,`SS1`,`SVFN`,) VALUES ($jid,$CL,$AD,$DT,$SS1,$SVFN)";
// I have tried stating the values as $X, '$X',....no difference
$result = mysqli_query($dbConnection, $query1);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($dbConnection) . ".";
}
$result = mysqli_query($dbConnection, $query2);
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($dbConnection) . ".";
}
$result = mysqli_query($dbConnection, $query3); // and so on
if (!$result) {
$flag = false;
echo "Error details: " . mysqli_error($dbConnection) . ".";
}
if ($flag) {
mysqli_commit($dbConnection);
echo "All queries were executed successfully";
} else {
mysqli_rollback($dbConnection);
echo "All queries were rolled back";
}
mysqli_close($dbConnection);
?>

PHP Fatal error: Could not queue new timer in Unknown on line 0

I write a simple web application for my compnay that can let user log in to arrange their work time. Besides, user can also view the report of he's or she's attandence that I use ajax to callback from java.jar. (We use java to analyze)I use Xampp to set up the server in virtual machine HyperV and it can run successfully at the begining but after twenty hours or more than one day it won't let anyone to log in.
I open the error.log shows that :
PHP Fatal error: Could not queue new timer in Unknown on line 0
. . . and than:
PHP Warning: mysqli_connect(): (HY000/2002): Unknown Error
I don't understand what can cause that happend and how to solve it.
I alreday know is when I restarted the apache server, it can still be used till that error happened.
My System Enviroment :
win7 64 bit HyperV
xampp Apache/2.4.18, php/7.0.6, mysql/ 5.1
Here is my code:
mysql_start.php
<?php
header("Content-Type:html;charset=utf-8");
$servername = "127.0.0.1";
$username = "root";
$password = "cc1234";
$dbname = "cc_tw000427";
$conn = null;
try {
$conn = new mysqli($servername, $username, $password, $dbname);
} catch (Exception $e) {
$error_message = "Connect Error (" .$conn->connect_errno ." )" . $conn->connect_error;
error_log($error_message, 3, "php_error_log");
header("location:login.php?err=$e");
}
$conn->set_charset("utf-8");
$strDBColLoingAccount = "AccountID";
checklogin.php
session_start();
include_once("mysql_start.php");
$yid = trim(filter_input(INPUT_POST, "yid"));
$passd = trim(filter_input(INPUT_POST,"passd"));
$strSql = "SELECT acc.*, b.String_10_1 FROM basicstoreinfomanageacc_sub acc,basicstoreinfo b
WHERE acc.$strDBColLoingAccount ='$yid' AND acc.String_50_1 = b.String_50_1";
$result = $conn->query($strSql);
$n = $result->num_rows;
if ($n == 0) {
header("Location:../desktop/login.php?err=1");
echo "Error 1";
exit();
}
while ($row = $result->fetch_assoc()) {
$passd_right = $row["AccountPwd"];
$user_id = $row["AccountID"];
$user_name = $row["AccountName"];
$user_dep_id = $row["String_10_1"];
$user_dep = $row['String_50_1'];
}
$result->close();
if (($passd_right == "") || ($passd_right == NULL)){
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
header("location:newpwd.php");
exit();
}
if ($passd == $passd_right) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
$_SESSION['loginOK'] = 'yes';
$_SESSION['year_i'] = date('Y',time());
$_SESSION['year_f'] = date('Y',time());
$_SESSION['month_i'] = date('m',time());
$_SESSION['month_f'] = date('m',time());
$_SESSION['day_i'] = date('d',time());
$_SESSION['day_f'] = date('d',time());
$_SESSION['Hour'] = date('Y-m-d G:i:s',strtotime('+6 hour'));
$_SESSION['user_dep_id'] = $user_dep_id;
$_SESSION['user_dep'] = $user_dep;
header("Location:../desktop/Punch.php");
} else {
header("Location:../desktop/login.php?err=1");
}
$conn->close();
?>
Next two *.php files are used to receive the post from the web.
The select.php is used to select the data from mysql than output in html tag.
The save.php is used to save the data post from web.
select.php
<?php
session_start();
include_once '../control/mysql_start.php';
$strYear = $_POST['year'];
$strMonth = $_POST['month'];
$strDay = $_POST['day'];
.
.//some codes
.
$strSql = "SELECT * FROM basicemploymentinfo bei WHERE bei.BelongStore = '". $_SESSION['user_dep']."'".
"AND ((bei.datetime_2 is null AND bei.datetime_3 is null) OR (bei.datetime_2 is null AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 is null)" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))) "
."AND bei.Active ='Y'";
$EmpId = array();
$EmpName = array();
if ($result = $conn->query($strSql)) {
while($row = $result->fetch_assoc()) {
array_push($EmpId, $row['String_20_1']);
array_push($EmpName, $row['String_20_2']);
.
.//some codes
.
}
}
$Emp = array_combine($EmpId, $EmpName);
$strSql = " SELECT Distinct date_format(DateTime_1, '%e') as date, AutoCheck
FROM hrotcheck
WHERE date_format(DateTime_1, '%Y-%m-%d') = '$newformat'
AND AutoCheck = 'C'
AND String_20_1 IN ($array_emp_id)";
if ($result = $conn->query($strSql)) {
$n = $result->num_rows;
if ($n > 0) { $checkboxVerify = 'C';}
}
$result->close();
foreach ($Emp as $EId => $EName)
{
.
.//some codes
.
$strSql = "SELECT RegularM_1, RegularM_2, FORMAT(OT_3, 1) as OT_3, TOM, TOTM, Notes, AutoCheck FROM hrotcheck where string_20_1 = '" . $EId . "' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result = $conn->query($strSql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$RegularM_1 = $row['RegularM_1'];
$RegularM_2 = $row['RegularM_2'];
$OT3 = $row['OT_3'];
$tom = $row['TOM'];
$totm = $row['TOTM'];
$notes = $row['Notes'];
}
}
$result->close();
.
.//I did a lot of SQL select and use that to create htmltable
.
$output .= '
<tr data-table="sub">
<td>'.$row['string_20_1'].'</td>
<td>'.$row['string_20_2'].'</td>
.
.//<td>...</td>
.
<td class="'.$condition16.'">'.$notes.'</td>
<td class="'.$condition17.'"></td>
</tr>
';
}
.
.//some codes
.
$strSql01 = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$row['string_20_1']."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result01 = $conn->query($strSql01);
if ($result01->num_rows > 0) {
while ($row01 = $result01->fetch_assoc()) {
.
.//some codes
.
}
}
$result01->close();
.
.//some codes
.
$result->close();
$conn->close();
echo $optionUse.'?'.$checkboxVerify.'?'.$output.'?'.$hasCheckDate;
?>
save.php
<?php
session_start();
include_once '../control/mysql_start.php';
$arrayObjs = $_POST;
.
.//some codes
.
$msDanger = '';
foreach($arrayObjs as $array)
{
foreach($array as $row)
{
$UserId = $row['UserId'];
$UserName = $row['UserName'];
.
.//some codes
.
$strSql = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
$result = $conn->query($strSql);
if( $result->num_rows > 0) {
if ($table == 'main') {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1', String_Assist01 ='$assist_1',String_Assist02='$assist_2' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
} else {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
}
$result = $conn->query($strSql);
} else {
$strSql = "INSERT INTO manufacturejobschedulingpersonal (string_20_1,string_20_2,YM,DateTime_1,String_10_1,String_Assist01,String_Assist02)".
"VALUES ( '$UserId', '$UserName', '$YM', '$DateTime_1', '$String_10_1','$assist_1','$assist_2')";
$result = $conn->query($strSql);
}
.
.//A lot of sql CRUD
.
}
}
$conn->close();
$last_line = exec('java -jar C:/CCERP/ChainCodeERP/ExtraModule/HRMultiOTCheck/HRMultiOTCheck.jar -ssa '.$javaDate.' ' .$javaDepId, $return_var);
echo 'Updated';
?>

How to add text from form into sql table?

In my flex application, I have a form which retrieves data from an SQL table and displays it in the textinput:
<s:Form id="form" includeIn="ShoppingList" x="223" y="353"
creationComplete="form_creationCompleteHandler(event)" defaultButton="{button}">
<s:FormItem label="Name">
<s:TextInput id="textInput" text="{getAllShoppinglistResult.lastResult[0].name}"/>
<s:TextInput id="textInput1" text="{getAllShoppinglistResult.lastResult[1].name}"/>
<s:TextInput id="textInput2" text="{getAllShoppinglistResult.lastResult[2].name}"/>
<s:TextInput id="textInput3" text="{getAllShoppinglistResult.lastResult[3].name}"/>
</s:FormItem>
<s:Button id="button" label="Submit" click="button_clickHandler(event)"/>
</s:Form>
In this case, there is just 2 items in the SQL table, the other 2 text input fields of free.
I want to be able to type text into the textinput and it saves it to the server.
protected function button_clickHandler(event:MouseEvent):void
{
items.name = textInput.text;
createShoppinglistResult.token = shoppinglistService1.createShoppinglist(name);
}
protected function createShoppinglistResult_resultHandler(event:ResultEvent):void
{
}
I'm unsure as to what goes into the createShoppinglist..* function.
I know that the PHP service is correct as currently it does save it to the server but it just saves NULL, I want it to save the textinput. I know that if it were a datagrid I could use AddItem() for an Array Collection, but I don't know what I could use for a form?
Maybe that will help! regards aktell
Unfortunately looks a bit like a mess! Here is a Link were you can see it much better - just towards the bottom!
http://board.flashkit.com/board/showthread.php?828493-php-gt-gt-mySQL-not-returning-data-as-XML
<?php
// init.php
// Script:
// Connecting to the MySQL DataBase Server & a DataBase.
/* ------------------------------------------------------------------------------------------------------------------ */
// MySQL DataBase Server Variables.
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
// DataBase Variable.
$db = 'webflash_createcartdb';
// Connect to MySQL DataBase Server.
$con = # mysql_connect("$mysql_host", "$mysql_user", "$mysql_pass")
or exit("Could not connect to MySQL DataBase Server! \n Select DB Error: " . # mysql_error());
$con = # mysql_select_db($db)
or exit( 'Can\'t select the Database is unavailable.' . # mysql_error());
return $con;
/* ------------------------------------------------------------------------------------------------------------------ */
?>
READ & WRITE:
// custInfoDetails.php
/* ------------------------------------------------------------------------------------------------------------------ */
header('Content-Type: text/xml');
/* ------------------------------------------------------------------------------------------------------------------ */
include("../Conn/init.php");
/* ------------------------------------------------------------------------------------------------------------------ /
// MAIN TABLE.
/ ------------------------------------------------------------------------------------------------------------------ */
if (isset($_POST['lastName'])) {
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$middleName = $_POST['middleName'];
$lastName = $_POST['lastName'];
$fullName = $_POST['fullName'];
$no = $_POST['no'];
$street1 = $_POST['street1'];
$street2 = $_POST['street2'];
$zip = $_POST['zip'];
$suburb = $_POST['suburb'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$email = $_POST['email'];
$userName = $_POST['userName'];
$password = $_POST['password'];
$userNameCopy = mysql_real_escape_string($_POST["userNameCopy"]);
$sql = 'INSERT INTO ' . $userNameCopy . '
(title, firstName, middleName, lastName, fullName, no, street1, street2, zip, suburb, city,
state, country, email, userName, password, now)
VALUES
("' . $title . '", "' . $firstName . '", "' . $middleName . '", "' . $lastName . '", "' . $fullName . '",
"' . $no . '", "' . $street1 . '", "' . $street2 . '", "' . $zip . '", "' . $suburb . '",
"' . $city . '", "' . $state . '", "' . $country . '", "' . $email . '",
"' . $userName . '", "' . $password . '", NOW() )';
$result = # mysql_query($sql);
if (!$result) { exit('Error performing the MAIN INSERT query.' . # mysql_error());
}
}
/* ------------------------------------------------------------------------------------------------------------------ */
$sql = "SELECT custcartinfoID, title, firstName, middleName, lastName, fullName, no, street1, street2,
zip, suburb, city, state, country, email, userName, password, now FROM ' . $userNameCopy . ' ";
$result = # mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . # mysql_errno() . " : " . # mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
exit($message);
}
/* ------------------------------------------------------------------------------------------------------------------ /
// XML READOUT.
/ ------------------------------------------------------------------------------------------------------------------ */
$xml = new DomDocument('1.0', 'UTF-8');
$root = $xml->createElement('allMessages');
$root = $xml->appendChild($root);
$result = # mysql_query($sql);
if ($result) {
if ( # mysql_num_rows($result) > 0) {
while ($row = # mysql_fetch_array($result)) {
$custcartinfoID = $row['custcartinfoID'];
$title = $row['title'];
$firstName = $row['firstName'];
$middleName = $row['middleName'];
$lastName = $row['lastName'];
$fullName = $row['fullName'];
$no = $row['no'];
$street1 = $row['street1'];
$street2 = $row['street2'];
$zip = $row['zip'];
$suburb = $row['suburb'];
$city = $row['city'];
$state = $row['state'];
$country = $row['country'];
$email = $row['email'];
$userName = $row['userName'];
$password = $row['password'];
$now = $row['now'];
// Message Element OPEN Node.
$itemElement = $xml->createElement('message');
$itemElement = $root->appendChild($itemElement);
// First Field.
$idElement = $xml->createElement('custcartinfoID', $custcartinfoID);
$idElement = $itemElement->appendChild($idElement);
$titleElement = $xml->createElement('title', $title);
$titleElement = $itemElement->appendChild($titleElement);
$firstNameElement = $xml->createElement('firstName', $firstName);
$firstNameElement = $itemElement->appendChild($firstNameElement);
$middleNameElement = $xml->createElement('middleName', $middleName);
$middleNameElement = $itemElement->appendChild($middleNameElement);
$lastNameElement = $xml->createElement('lastName', $lastName);
$lastNameElement = $itemElement->appendChild($lastNameElement);
$fullNameElement = $xml->createElement('fullName', $fullName);
$fullNameElement = $itemElement->appendChild($fullNameElement);
$noElement = $xml->createElement('no', $no);
$noElement = $itemElement->appendChild($noElement);
$street1Element = $xml->createElement('street1', $street1);
$street1Element = $itemElement->appendChild($street1Element);
$street2Element = $xml->createElement('street2', $street2);
$street2Element = $itemElement->appendChild($street2Element);
$zipElement = $xml->createElement('zip', $zip);
$zipElement = $itemElement->appendChild($zipElement);
$suburbElement = $xml->createElement('suburb', $suburb);
$suburbElement = $itemElement->appendChild($suburbElement);
$cityElement = $xml->createElement('city', $city);
$cityElement = $itemElement->appendChild($cityElement);
$stateElement = $xml->createElement('state', $state);
$stateElement = $itemElement->appendChild($stateElement);
$countryElement = $xml->createElement('country', $country);
$countryElement = $itemElement->appendChild($countryElement);
$emailElement = $xml->createElement('email', $email);
$emailElement = $itemElement->appendChild($emailElement);
$userNameElement = $xml->createElement('userName', $userName);
$userNameElement = $itemElement->appendChild($userNameElement);
$passwordElement = $xml->createElement('password', $password);
$passwordElement = $itemElement->appendChild($passwordElement);
// Last Field.
$nowElement = $xml->createElement('now', $now);
$nowElement = $itemElement->appendChild($nowElement);
}
}
// Message Element CLOSING Node.
else {
$messageElement = $xml->createElement('message','There are no posts.');
$messageElement = $root->appendChild($messageElement);
}
}
else {
$messageElement = $xml->createElement('message', #mysql_error());
$messageElement = $root->appendChild($messageElement);
}
// Return the XML Document.
echo $xml->saveXML();
/* ------------------------------------------------------------------------------------------------------------------ */
// CLOSE DATABSE.
// Close DataBase Server Connection!
# mysql_close($con);
/* ------------------------------------------------------------------------------------------------------------------ */
?>
READ ONLY:
// select.php
/* ------------------------------------------------------------------------------------------------------------------ */
// First, this script uses the header() function to tell the web server that the return is going to be XML.
header('Content-Type: text/xml');
/* ------------------------------------------------------------------------------------------------------------------ */
// Connecting with MySQL DataBase Server & a DataBase.
include("init.php");
/* ------------------------------------------------------------------------------------------------------------------ /
// MAIN TABLE.
/ ------------------------------------------------------------------------------------------------------------------ */
// SELECT more than one Table !
/* $query="SELECT movie.movie_name, movietype.movietype_label FROM movie, movietype
WHERE movie.movie_type = movietype.movietype_id
AND movie.movie_year>1990
ORDER BY movie_type"; */
$sql = 'SELECT customerID, title, firstname, middlename, lastname, no, street1, street2, zip, suburb, city,
state, country, email, emailpriv, emailbus, url1, url2, note, now FROM customerdetails';
$result = # mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . # mysql_errno() . " : " . # mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
exit($message);
}
/* ------------------------------------------------------------------------------------------------------------------ /
// XML READOUT.
/ ------------------------------------------------------------------------------------------------------------------ */
$xml = new DomDocument('1.0', 'UTF-8');
$root = $xml->createElement('customerDetails');
$root = $xml->appendChild($root);
$result = # mysql_query($sql);
if ($result) {
if ( # mysql_num_rows($result) > 0) {
while ($row = # mysql_fetch_array($result)) {
$customerID = $row['customerID'];
$title = $row['title'];
$firstname = $row['firstname'];
$middlename = $row['middlename'];
$lastname = $row['lastname'];
$no = $row['no'];
$street1 = $row['street1'];
$street2 = $row['street2'];
$zip = $row['zip'];
$suburb = $row['suburb'];
$city = $row['city'];
$state = $row['state'];
$country = $row['country'];
$email = $row['email'];
$emailpriv = $row['emailpriv'];
$emailbus = $row['emailbus'];
$url1 = $row['url1'];
$url2 = $row['url2'];
$note = $row['note'];
$now = $row['now'];
// Message Element OPEN Node.
$itemElement = $xml->createElement('information');
$itemElement = $root->appendChild($itemElement);
// First Field.
$idElement = $xml->createElement('customerID', $customerID);
$idElement = $itemElement->appendChild($idElement);
$titleElement = $xml->createElement('title', $title);
$titleElement = $itemElement->appendChild($titleElement);
$firstnameElement = $xml->createElement('firstname', $firstname);
$firstnameElement = $itemElement->appendChild($firstnameElement);
$middlenameElement = $xml->createElement('middlename', $middlename);
$middlenameElement = $itemElement->appendChild($middlenameElement);
$lastnameElement = $xml->createElement('lastname', $lastname);
$lastnameElement = $itemElement->appendChild($lastnameElement);
$noElement = $xml->createElement('no', $no);
$noElement = $itemElement->appendChild($noElement);
$street1Element = $xml->createElement('street1', $street1);
$street1Element = $itemElement->appendChild($street1Element);
$street2Element = $xml->createElement('street2', $street2);
$street2Element = $itemElement->appendChild($street2Element);
$zipElement = $xml->createElement('zip', $zip);
$zipElement = $itemElement->appendChild($zipElement);
$suburbElement = $xml->createElement('suburb', $suburb);
$suburbElement = $itemElement->appendChild($suburbElement);
$cityElement = $xml->createElement('city', $city);
$cityElement = $itemElement->appendChild($cityElement);
$stateElement = $xml->createElement('state', $state);
$stateElement = $itemElement->appendChild($stateElement);
$countryElement = $xml->createElement('country', $country);
$countryElement = $itemElement->appendChild($countryElement);
$emailElement = $xml->createElement('email', $email);
$emailElement = $itemElement->appendChild($emailElement);
$emailprivElement = $xml->createElement('emailpriv', $emailpriv);
$emailprivElement = $itemElement->appendChild($emailprivElement);
$emailbusElement = $xml->createElement('emailbus', $emailbus);
$emailbusElement = $itemElement->appendChild($emailbusElement);
$url1Element = $xml->createElement('url1', $url1);
$url1Element = $itemElement->appendChild($url1Element);
$url2Element = $xml->createElement('url2', $url2);
$url2Element = $itemElement->appendChild($url2Element);
$noteElement = $xml->createElement('note', $note);
$noteElement = $itemElement->appendChild($noteElement);
// Last Field.
$nowElement = $xml->createElement('now', $now);
$nowElement = $itemElement->appendChild($nowElement);
}
}
// Message Element CLOSING Node.
else {
$messageElement = $xml->createElement('information','There are no posts.');
$messageElement = $root>appendChild($messageElement);
}
}
else {
$messageElement = $xml->createElement('information', #mysql_error());
$messageElement = $root>appendChild($messageElement);
}
echo $xml->saveXML();
?>

PHP variable variables in MySQL query

This code works fine: $batsman1name is inserted as a new value in the correct row in the database.
for($count = 1; $count <= 22; ++$count)
{
$setbattingid = 'batsman' . $count . 'battingid';
$$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
$setname = "batsman" . $count . "name";
$$setname = mysql_real_escape_string($_POST[$setname]);
$query = "UPDATE batting_new SET batsmanname = NULLIF('$batsman1name', '') WHERE battingid = '$batsman1battingid'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
}
With this code the database is not updated, but the varaible variables $$setname and $$setbattingid do contain the same values as $batsman1name and $batsman1battingid above.
for($count = 1; $count <= 22; ++$count)
{
$setbattingid = 'batsman' . $count . 'battingid';
$$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
$setname = "batsman" . $count . "name";
$$setname = mysql_real_escape_string($_POST[$setname]);
$query = "UPDATE batting_new SET batsmanname = NULLIF('$$setname', '') WHERE battingid = '$$setbattingid'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
}
Any ideas? Let me know if I haven't explained my question very well? Thanks.
You should use :
$query = "UPDATE batting_new SET batsmanname = NULLIF('${$setname}', '') WHERE battingid = '${$setbattingid}'";
As described here : http://php.net/manual/language.variables.variable.php

Categories