Variable in a mysql query - php

for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
include "dbconnect.php";
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
$fetch = mysql_fetch_array($selectquery);
$tid = $fetch['tid']; $username = $fetch['username']; $c_month = $fetch['month']; $c_day =$fetch['day']; $c_year = $fetch['year'];
$c_month2 = $fetch['month2']; $c_day2 =$fetch['day2']; $c_year2 = $fetch['year2'];
$pickup = "".$c_month."/".$c_day."/".$c_year."";
$return = "".$c_month2."/".$c_day2."/".$c_year2."";
$pickuploc = "".$fetch['pickupret']." "." ".$fetch['speclocation']."";
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
$vehicle1 = $fetch['vehicle1'];
$datesent = date("n j, Y; G:i"); ;
$rand = rand(98765432,23456789);
include "vehicledbconnect.php";
$vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");
$getvquery = mysql_fetch_array($vquery);
$maxcars = $getvquery['maxcars'];
$carsleft = $getvquery['carsleft'];
if ($carsleft == 0) {
echo '
<script language="JavaScript">
alert("Cannot move reservation to Pending for payment status. No available vehicles left for this reservation.");
</script>';
echo "$vehicle1";
}
Hi guys my problem here is that the $vehicle is not returning its values if it is inserted in a database query ($vquery = mysql_query("SELECT * FROM vehicletbl WHERE vehicle = '$vehicle1'");) but if it is echoed, it return its value. The logic here is that it will select all the values from vehicletbl wherein the value of any values in 'vehicle' column will be equal to the $vehicle1. Thanks for the help!

You've got ZERO error handling on your queries. Try adding some debugging to the query calls:
$result = mysql_query(...) or die(mysql_error());
The rest of the code is ugly, but looks "ok", so start looking at WHY you're not getting anything back from the queries.
Never ever assume a query succeeds.

try this to debug :
$sql = "SELECT * FROM vehicletbl WHERE vehicle = '" . $vehicle1 . "'";
$vquery = mysql_query($sql) or die(mysql_error() . "\n<br>$sql");
thats what i do to find errors in my sql.

Noob programmer ? Here are some things to know :
for ($i=0; $i<$count; $i++) {
$appid = $chk[$i];
// Replaced By ...
foreach($chk as $appid){
http://php.net/manual/en/control-structures.foreach.php
// Include the file before the loop ! You're including 20 times your file, but you just need to do it once ! Another thing to know:
include_once("dbconnect.php");
http://php.net/manual/en/function.include-once.php
$desti = "".$fetch['destination']." "." ".$fetch['location']."";
// WHY ?? Isn't that easier to do this ?
$desti = $fetch['destination']." ".$fetch['location'];
And security :
// Don't forget to escape your variables before putting it in mysql queries
$appid = mysql_real_escape_string($appid);
$selectquery = mysql_query("SELECT * FROM regform_admin WHERE tid = '$appid'");
Best way to defend against mysql injection and cross site scripting
There are other remarks, but try to improve those points first !

Related

Prevent text from being interpreted as a number

I have a PHP/SQL app that processes invoices. Recently, I had an invoice number come in that is not being processed as text, rather as a large exponential number when I do an insert/update on associated SQL tables. For example, take an invoice number that looks like this: 123E456. PHP will try to convert this to an extremely large number due to the 'E' being bookended by numbers.
I am leaning towards this being a PHP issue because when I look at the SQL being sent to the server, it is being scripted without quotes, 123E456 rather than '123E456'.
I have tried multiple ways to try and force it to be text, but nothing seems to work.
If I put single quotes around the string, I get double single quotes in the SQL.
strval() also does not work
the issue might be in the SQL interpreter, but not entirely sure
Right now, I am instructing my clerks to put a space between the E and the numbers, which works for now. But, I am hoping to address this specific issue in the code rather than have the clerk remember to manage it on their end.
Can anyone help with how to force this as being text in the SQL clause?
OK, the code is rather my own style and is based on retrieving a dummy record (the table has 178 columns) and then populating the values into the elements that need updated. It then creates the SQL from the array and does the update. Most of this is just pre-processing to get the values needed. The database being used is Oracle.
function processF0411Z1($id, $user){
include_once $_SERVER['DOCUMENT_ROOT'].'/truck/inc/base.inc.php';
$b = '\' \'';
$z = 0;
$co = get_route_company($id);
$usrsql='SELECT `userID` from `user` where `id` = ' . $user;
$usr = openRecordset_Fetch_Assoc($usrsql);
if($usr[0]==1)$userid = $usr[1]['userID'];
else $userid = $_SESSION['username'];
$jul = date2jul(getdate());
$tjul= getJulTime(getdate());
$sql = "SELECT a.`id`, a.`carrierInvoice`, a.`carrierNbr`, a.`ivd`, a.`dgl`, b.`bol`, b.`obj_acct`, b.`allocation` FROM `route13` a inner join `route131` b on(a.`id` = b.`id`)WHERE a.`id`=".$id;
$myArr = openRecordset_Fetch_Assoc($sql);
if(isset($myArr) && $myArr[0]>0){
$carr = $myArr[1]['carrierNbr'];
$carrsql = 'select `CarrierName` from `Carriers` where `CarrierNbr` = '. $carr;
$carr_res = openRecordset_Fetch_Assoc($carrsql);
if($carr_res[0]==1)$carrName = $carr_res[1]['CarrierName'];
else $carrName = $carr;
// get the next number in the EDI Batch sequence
$nn = getJDEZFileNN();
// get the base associated array of the F0411Z1 table
$msSQL = 'SELECT * FROM PRODDTA.F59411Z1 WHERE VLEDUS=\'TRUCK\' AND VLEDBT=1';
$F0411Z1 = oracle_fetch_array($msSQL);
for($i=1;$i<=$myArr[0];$i++){
// test to see if this record exists
$tsql = "select * from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$tres = oracle_fetch_array($tsql);
if($tres[0]>0){
$dsql = "delete from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$count = oracle_update($dsql);
if($count === $tres[0]){
$count = $count;
}
}
$an8_sql = 'SELECT aban85 FROM PRODDTA.F0101 WHERE aban8='.$myArr[$i]['carrierNbr'];
$aban85 = oracle_fetch_array($an8_sql);
$dp = date_parse($myArr[$i]['ivd']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$ivd = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$dp = date_parse($myArr[$i]['dgl']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$inv_no = strval($myArr[$i]['carrierInvoice']);
// index: ("VLEDUS", "VLEDBT", "VLEDTN", "VLEDLN")
$gld = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$F0411Z1[1]['VLEDUS'] = '\''.strtoupper($user).'\'';//$_SESSION['userid'];
$F0411Z1[1]['VLEDLN'] = $i*1000;
$F0411Z1[1]['VLEDBT'] = $nn[1]['NNN006'];
$F0411Z1[1]['VLAN8'] = $myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLPYE'] = $aban85[1]['ABAN85'];//$myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLDIVJ'] = $ivd;//$myArr[$i]['ivd'];
//$F0411Z1[1]['VLDSVJ'] = $jul;
$F0411Z1[1]['VLDGJ'] = $gld;
$F0411Z1[1]['VLCO'] = $co;
$F0411Z1[1]['VLKCO'] = $co;
$F0411Z1[1]['VLAG'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLAAP'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLVINV'] = $inv_no;// <-- This element is the issue
$F0411Z1[1]['VLRMK'] = (strlen($carrName)>30?substr($carrName,0,29):$carrName);
$F0411Z1[1]['VLGLBA'] = '00573714';
$F0411Z1[1]['VLMCU'] = '1';
$F0411Z1[1]['VLTORG'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLUSER'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLPID'] = 'TRUCK';
$F0411Z1[1]['VLUPMJ'] = $jul;
$F0411Z1[1]['VLUPMT'] = $tjul;
$F0411Z1[1]['VLJOBN'] = 'TRUCK';
$F0411Z1[1]['VLURAB'] = $id;
$F0411Z1[1]['VLURRF'] = $myArr[$i]['bol'];
$z=1;
for($x=1;$x<=$F0411Z1[0];$x++){
$val1 = $F0411Z1[$x];
// first element of array is the counter, skip it
if($val1 != 1){
foreach($F0411Z1[1] as $val){
if($z==1){
$stmt = 'VALUES('.$val;
$z=99;
}
else{
if(!is_numeric($val))$val = '\''.$val.'\'';
$stmt .= ','.$val;
}
}
$stmt .= ')';
//$msSQL = 'INSERT INTO PS_PRODUCTION.PRODDTA.F0411Z1 '.$stmt;
$msSQL = 'INSERT INTO PRODDTA.F0411Z1 '.$stmt;
$count = oracle_update($msSQL);
if($count != 1) return 36;
}
}
}
}
else return 36;
return 0;
}
You can use the strval() method to cast the number as a string.
$number = 123E456;
$string = strval($number);
Or just force it to cast as a string
$string = (string) $number;

cannot select a row in mysql

EDIT1 : used double quotes and single quotes but I am getting same error.
EDIT2 : same query is returning me result in mysql shell
I am selecting a row from a table.
if(!isset($_GET['title']) || !isset($_GET['user'])){
echo "hi"; //something come here
}
else{
$title = $_GET['title'];
$title = mysqli_real_escape_string($conn,$title);
$user = $_GET['user'];
$user = mysqli_real_escape_string($conn,$user);
echo $title ;
echo $user ;
// tried giving value directly to test but no luck
$query = "SELECT * FROM site WHERE client=\"Chaitanya\" && title=\"werdfghb\" ";
$result5 = mysqli_query($conn,$query) or die(mysqli_error());
$count = mysqli_num_rows($result5);
echo $count ;
while($result9 = mysqli_fetch_array($result5)){
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
include ( 'counter.php');
addinfo($page);
}
In my database there is a row with columns title and client and the values I entered are in that row but when I echo count(no of rows) it is showing zero.
Is there anything wrong with code ?
The error you are getting is due to the line
$page = $kk;
in this code $kk is not declared previously. The defined $kk is in the while loop scope.
declare the variable like this in the outer scope from the while loop
...
$kk = null;
while($result9 = mysqli_fetch_array($result5)) {
$kk = $result9['url'];
echo $kk ;
}
$page = $kk;
...
Error on Fetching Data
You have to crack you SQl into smaller pieces and test the code like this.
run the query SELECT * FROM site without any where and get the count
run the query SELECT * FROM site WHERE client='Chaitanya' and get the count
SELECT * FROM site WHERE title='werdfghb' and check the count
Then run the whole query
And see the results. This way u can find out in where the issue is in your SQL code. I prefer you use the mysql client to execute this queries
As I pointed out in my comment, $kk is undefined in the $page = $kk;, since it is declared in the while loop.
Do something like:
$kk = ''; //can also do $kk=NULL; if you want.
while($result9 = mysqli_fetch_array($result5)) {
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
try this one
$client = "Chaitanya";
$title = "werdfghb";
$query="SELECT * FROM site WHERE client='".$client."' and title='".$title."' ";
you can also use this
$query="SELECT * FROM site WHERE client={$client} and title={$title} ";

PHP MYSQL filling an array with variables and change the field names

I'm new to PHP and MySQL. I need to fill an array and I want to change the field names and I can't achieve it.
My code:
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $grow['descr_bien'];
$ubicacion = $grow['ubicacion'];
$marca = $grow['marca'];
$modelo = $grow['modelo'];
$ano = $grow['ano'];
$DescrMoneda = $grow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data = array(array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor),array($hrow));
}
$pdf->ezTable($data,$cols,'Bienes:',array('gridlines'=> EZ_GRIDLINE_DEFAULT,'shadeHeadingCol'=>array(0.6,0.6,0.5),'showBgCol'=>1,'width'=>500,'cols'=>array('valor'=>array('justification'=>'right'))));
Okay first of all I am going to assume you have managed to set up $dcConn to get your database connection. If not go look at http://php.net/manual/en/function.mysql-connect.php
Next your while statement is storing each value in $hrow but you seem to be assigning everything to grow.
Your next issue is that $data will be overwritten for every row in your result.
From what I understand you will be wanting something along the lines of
$querystr = "SELECT DISTINCT descr_bien,ubicacion,marca,modelo,ano,DescrMoneda,valor FROM bienes,Moneda WHERE bienes.IdMoneda = Moneda.IdMoneda AND bienes.Idpropuesta = '" . addslashes($Idpropuesta) . "'";
$result3 = mysql_query($querystr,$dbConn);
while($hrow = mysql_fetch_assoc($result3)){
$descr_bien = $hrow['descr_bien'];
$ubicacion = $hrow['ubicacion'];
$marca = $hrow['marca'];
$modelo = $hrow['modelo'];
$ano = $hrow['ano'];
$DescrMoneda = $hrow['DescrMoneda'];
$valor = number_format($grow['valor'],2,",",".");
$data[] = array('Descripción'=>$descr_bien,'ubicacion'=>$ubicacion,'marca'=>$marca,'modelo'=>$modelo,'Año'=>$ano,'DescrMoneda'=>$DescrMoneda,'valor'=>$valor));
}
I do not know about the last line at all so left it out.
One other suggestion that using the PDO library to access the mysql database would usually be a better idea unless this all that the php will ever need to do.
I hope this helps

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

VB if-statement in PHP

I need help to convert the following Visual Basic statement into a PHP equivalent:
If Not IsNumeric(siteid) Then
dr = GetDataReader("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = '" & siteid & "'")
If Not dr.HasRows Then
Response.Write(sep & siteid & "=" & siteid)
sep = ","
End If
If Not dr Is Nothing Then
dr.Close()
End If
End If
I need help with the If statements more than anything.
Thanks
See here for the docs you need to check, also here
Seems like you also need to learn how to use mySQL in PHP
The code is relatively easy, in its simplest step- almost line for line from what you have to help you see the transformation to PHP (there are better implementations):
$siteid = 1; // where 1 is the value of siteid, PHP vars are prefixed with '$'
// you also could do
// if(!isset($siteid){
// if(!$siteid){
if(!is_numeric($siteid){
// there is no site ID, so get it from the DB
// Make a MySQL Connection
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
// Run your query
$result = mysql_query("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = ".$siteid)
or die(mysql_error());
if(mysql_num_rows($result)>0){
// rows returned
//assuming only one row is returned, with your siteid value
$row = mysql_fetch_array( $result );
$siteid=$row['siteid'];
}else{
// no rows returned
// do something
}
}else{
// $siteid is already a valid value
}
AN if statement goes something like this:
if(someexpression){
$yourcode = "your things";
}
quick mockup of your code:
if(!is_numeric($siteid){
//sql call
$result = yourdb->query('SELECT');
if(!$result){
echo "error";
}
}
if(!$this->IsNumeric($siteid))
{
$dr = $this->GetDataReader("SELECT siteid FROM nwsite WITH (NOLOCK) WHERE mac_address = $siteid");
if(!$dr->hasRows())
{
echo "$sep$siteid = $siteid";
$sep = " , ";
}
if(!is_null($dr))
{
$dr->close();
}
}
Following code may help you:
if (!is_numeric($siteid)) {
$res = mysql_query("SELECT siteid FROM nwsite WHERE mac_address = " . mysql_real_escape_string($siteid));
$rows = mysql_fetch_assoc($res);
if (count($rows) == 0) {
print($sep . $siteid . "=" . $siteid);
$sep = ',';
}
}

Categories