VB if-statement in PHP - 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 = ',';
}
}

Related

running a query inside a loop to do another loop

Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id

Very slow PHP - MySQL script

I am new at using PHP-MySQL. I have two MySQL tables:
Concreteness: A table that contains concreteness scores for 80K words
Brian: A table with 1 million rows, each containing one or two words.
I have a small PHP script that takes each row in "Brian", parses it, looks for the scores in "Concreteness" and records it in "Brian."
I have been running this script with several other tables that had 300-400k rows with each hundreds of words. "Brian" is different because it has 1 million rows with 1 or 2 words per row. For some reason, my script is SUPER slow with Brian.
Here is the actual script:
<?php
include "functions.php";
set_time_limit(0); // NOTE: no time limit
if (!$conn)
die('Not connected : ' . mysql_error());
$remove = array('{J}','{/J}','{N}','{/N}','{V}','{/V}','{RB}','{/RB}'); // tags to remove
$db = 'LCM';
mysql_select_db($db);
$resultconcreteness = mysql_query('SELECT `word`, `score` FROM `concreteness`') or die(mysql_error());
$array = array(); // NOTE: init score cache
while($row = mysql_fetch_assoc($resultconcreteness))
$array[strtolower($row['word'])] = $row['score']; // NOTE: php array as hashmap
mysql_free_result($resultconcreteness);
$data = mysql_query('SELECT `key`, `tagged` FROM `brian`') or die(mysql_error()); // NOTE: single query instead of multiple
while ($row = mysql_fetch_assoc($data)) {
$key = $row['key'];
$tagged = $row['tagged'];
$weight = $count = 0;
$speech = explode(' ', $tagged);
foreach ($speech as $word) {
if (preg_match('/({V}|{J}|{N}|{RB})/', $word, $matches)) {
$weight += $array[strtolower(str_replace($remove, '', $word))]; // NOTE: quick access to word's score
if(empty($array[strtolower(str_replace($remove, '', $word))])){}else{$count++;}
}
}
mysql_query('UPDATE `brian` SET `weight`='.$weight.', `count`='.$count.' WHERE `key`='.$key, $conn) or die(mysql_error());
// Print out the contents of the entry
Print "<b>Key:</b> ".$info['key'] . " <br>";
}
mysql_free_result($data);
?>
I guess the real problem is the 1 million mysql update statements you fire to the database. Consider bundling the update statements (and also remove the print):
$i=0;
while ($row = mysql_fetch_assoc($data)) {
// ... left out the obvious part
$sql .= "'UPDATE `brian` SET `weight`='.$weight.', `count`='.$count.' WHERE `key`='.$key;";
$i++;
if ($i%1000 == 0) {
mysql_query($sql) or die(mysql_error());
$i=0;
$sql = "";
}
}
// remember to save the last few updates
mysql_query($sql) or die(mysql_error());

No result being displayed when running this query

I have to create a dynamic query based on the value received by the user's input, the value of the variables are posted by GET
When I simply run this
$qry = "SELECT* FROM LAPTOP WHERE 1=1";
$resul = mysqli_query($qry);
retrieve($resul);
all the content of this table are displayed without any error,(retrieve function here displays all the results based on the query) but when I try to modify it like this, I get a blank page
$qry = "SELECT * FROM LAPTOP WHERE 1=1";
if(!empty($company))
{
$qry .= " AND company='$company'" ;
}
if(!empty($cpu))
{
$qry.= " AND cpu='$cpu' " ;
}
if(!empty($lifestyle))
{
$qry.= " AND lifestyle='$lifestyle' " ;
}
if(!empty($display))
{
$qry.= " AND display='$display'" ;
}
if(!empty($ram))
{
$qry.= " AND ram='$ram' " ;
}
if(!empty($HDD))
{
$qry.= " AND HDD='$HDD' " ;
}
echo $qry;
$result= mysqli_query($qry) || die(mysqli_error()) ;
retrieve($result) ;
$p = basename($_SERVER['REQUEST_URI']) ;
The result of echo $qry; is as expected, it displays this
SELECT * FROM LAPTOP WHERE 1=1 AND company='Asus' AND cpu='intel i3'
Is there a way to correct this? The reason I tried using WHERE 1=1 clause is that when all the variables are equal to NULL then the query returns all the rows from the table.
i guess you have no data in your database matched with your conditions . OR you have case sensitive with names.
example :
cpu='Intel i3' // with big I
cpu='intel I3' // with big I
cpu='intel i3' // double space.
OR if you have big string , think to use LIKE
$qry.= " AND cpu LIKE '%$cpu%' " ;
Is this a typo also ($resul_T_)?
$resul = mysqli_query($qry);
retrieve($resul);
How you managed to lose that 't' and later get it back? ;)
As others have pointed out it may simply be that your query does not match any records.
Anyway what I usually do in a similar case is put all the conditions in an array, and then implode the array with 'AND'. That way you don't have to bother with 1=1 and it doesn't matter whether you have 0, 1 or more conditions.
<?php
$qry = "SELECT * FROM LAPTOP";
$conditions = array();
$cpu = 'Intel';
$ram = '24GB';
if(!empty($cpu))
{
$conditions[] = "cpu='$cpu'";
}
if(!empty($lifestyle))
{
$conditions[] = "lifestyle='$lifestyle'";
}
if(!empty($display))
{
$conditions[] = "display='$display'";
}
if(!empty($ram))
{
$conditions[] = "ram='$ram'";
}
if(!empty($HDD))
{
$conditions[] = "HDD='$HDD'";
}
if( count( $conditions ) > 0 )
{
$qry .= " WHERE ";
$qry .= implode( " AND ", $conditions );
}
print_r($qry);
?>

Variable in a mysql query

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 !

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories