Issues with Multiple PHP variables in an SQL statement - php

My problem is i am trying to get 3 variables from the URL, they echo the correct information so i know that my $_GET's are working fine, The first $SC1 and $SC2 both work fine but the 3rd one in the SQL statement Dosnt.
If i replace
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = '". $SC3 ."' ");
with
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = 'apple' ");
it works fine but i know $SC3 = apple because i can echo the variable and its apple, please help im pulling my hair out. Heres the rest of the code regarding this.
Note: This is a search function that basis itself on which link people click in my websites menu and takes into consideration when people first click on the website so it displays all items in it.
require ('..\connect_db.php') ;
$SC1 = mysql_real_escape_string($_GET['sc1']); echo $SC1;
$SC2 = mysql_real_escape_string($_GET['sc2']); echo $SC2;
$SC3 = mysql_real_escape_string($_GET['sc3']); echo $SC3;
if ($SC1 && $SC2 && $SC3 = '') {
$thestatement = ('SELECT * FROM asset_records');}
else {;
$thestatement = ("SELECT * FROM asset_records WHERE a_catagory = '".$SC1."' AND ".$SC2." = '". $SC3 ."' ");
}
$result = mysql_query('' .$thestatement. '') or die(mysql_error());

You are emptying $SC3 in the if condition.

Related

$ _GET missing in pagination

I have 2 files, the first one:
gives me the list of products
The second one:
- information relating to the product, therefore as an information page
In the first file, I implement a <a> tag, to redirect to the second file
and the variable: $id_evidenza = $row_ListaEvidenze['ID_evidenza'];
<a href="edit_evidenza.php?id=<?php echo $id_evidenza; ?>&te=<?php echo $_GET['te']; ?>" title="Modifica">
<strong><?php echo outputDecode($row_ListaEvidenze['cod_evidenza']); ?></strong>
</a
make a select query, and take my variable:
$myid_processo = "-1";
if (isset($_GET['id'])) {
$myid_processo = $_GET['id'];
}
//42320819($database_riskmanagement,$riskmanagement);
$query_processo = sprintf("SELECT * FROM tev_Evidenze WHERE tev_Evidenze.id_struttura = ".$id_str." AND tev_Evidenze.ID_evidenza = %s", GetSQLValueString($myid_processo, "int"));
$processo = mysqli_query($riskmanagement, $query_processo) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $query_processo);
$row_processo = mysqli_fetch_assoc($processo);
$totalRows_processo = mysqli_num_rows($processo);
with a do / while loop, I show the results on screen and it's ok.
Now the problems begin, because right now from the page where there are the list of products, we are in the product info page, they asked me, to implement a navigation system, which gives the possibility that if I am inside the product A, going back and forth I can scroll through the other products, without going over the product list page, and so I did by implementing this navigation system:
if($_GET['te']==""){
$sel_tipo_acc = " (ev.id_tipo_accreditamento = 0)";
}else{
$sel_tipo_acc = " (ev.id_tipo_accreditamento = ".$_GET['te'].")";
}
$my_ric_att = searchControl(trim($_GET['ric_att']));
$txt_ric = "";
$txt_ric = "Risultati per ";
$r_sql = "SELECT * FROM tev_Evidenze AS ev LEFT JOIN tev_Fatt_crit AS fc
ON fc.ID_fatt_crit = ev.id_fatt_crit
WHERE ev.id_struttura = ".$_SESSION['str']." AND ".$sel_tipo_acc." AND ";
if ($_GET['facr'] != ""){
$r_sql .= " fc.ID_fatt_crit = ".$_GET['facr']." AND ";
}
$r_sql .= " ((ev.cod_evidenza LIKE '%" .$my_ric_att. "%') OR (ev.desc_evidenza LIKE '%" .$my_ric_att. "%')) ";
$txt_ric .= trim($_GET['ric_att']) ;
$r_sql .= " ORDER BY fc.ordine_fatt_crit, ev.cod_evidenza, ev.ordine_evidenza";
$txt_ric .= "<br>";
if($_GET['v']=="all"){
$paginazione = 1;
}else{
$paginazione = 1;
}
$maxRows_ListaEvidenze = $paginazione;
$pageNum_ListaEvidenze = 0;
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
$startRow_ListaEvidenze = $pageNum_ListaEvidenze * $maxRows_ListaEvidenze;
//42320819($database_riskmanagement, $riskmanagement);
$query_ListaEvidenze = $r_sql;
$query_limit_ListaEvidenze = sprintf("%s LIMIT %d, %d", $query_ListaEvidenze, $startRow_ListaEvidenze, $maxRows_ListaEvidenze);
$ListaEvidenze = mysqli_query($riskmanagement, $query_limit_ListaEvidenze) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $v_sql);
$row_processo = mysqli_fetch_assoc($ListaEvidenze);
if (isset($_GET['totalRows_ListaEvidenze'])) {
$totalRows_ListaEvidenze = $_GET['totalRows_ListaEvidenze'];
} else {
$all_ListaEvidenze = mysqli_query($riskmanagement, $query_ListaEvidenze);
$totalRows_ListaEvidenze = mysqli_num_rows($all_ListaEvidenze);
}
$totalPages_ListaEvidenze = ceil($totalRows_ListaEvidenze/$maxRows_ListaEvidenze)-1;
$queryString_ListaEvidenze = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_ListaEvidenze") == false &&
stristr($param, "totalRows_ListaEvidenze") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_ListaEvidenze = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_ListaEvidenze = sprintf("&totalRows_ListaEvidenze=%d%s", $totalRows_ListaEvidenze, $queryString_ListaEvidenze);
I have the problem in my url, I can't get all the necessary parameters in $ _GET, that is, if for example I go from product A to that B, I get this:
pageNum_ListaEvidenze=5&totalRows_ListaEvidenze=76&id=340&te=5
pageNum_ListaEvidenze=6&totalRows_ListaEvidenze=76&id=340&te=5
where the only thing that changes is the number after: pageNum_ListaEvidenze=
displaying another record, but the id is always stopped at the first record, I have this problem from this snippet of code, which I posted before:
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
how do i make everything dynamic in the url?
I really understand your issue , but here is a better solution that can make the life easy .
Let's suppose that currently , you are on the info page(Page B as you describe) that show the product information .
To swip for the next product , or previous , you can try to do this :
Normaly , one the info page , you are able to get the id of the current product
$currentProductID = $_GET['id'];
Think to create a method that give you the id of the next product , the query should be like :
SELECT id FROM `product` WHERE `id` > $currentProductID limit 1
This will return the id of the next product , and then redirect to the B page with this id returned using php redirection or by clicking on the tag etc .
To do that for the previous product , just inverse the query above
with <.
Hope that help you .

Mysqli query doesn't work with id from another table

I have this php script.
$cwZ = count($wiegen_zutat);
$cwM = count($wiegen_menge);
$cwS = count($wiegen_schritt);
if($cwM == $cwS and $cwM == $cwZ and $cwZ == $cwS){
for($x = 0; $x < $cwZ; $x++){
$aktZuat = $wiegenZutat[$x];
$qr = "SELECT ID_Zutat FROM Zutaten WHERE Name='$aktZutat' LIMIT 1";
$id_get = mysqli_query($verbindung,$qr );
$id = mysqli_fetch_array($id_get);
$zuatenID = $id['ID_Zutat'];
echo $id['ID_Zutat'];
echo $zutatenID;
$sql3 = "INSERT INTO Wiegen (ID_Zutat, Menge) VALUES ('$zutatenID', '$wiegenMenge[$x]')";
$wiegenEintragen = mysqli_query($verbindung, $sql3);
}
}
$wiegen_zutat, _menge, _schritt are all three arrays which contain the information from my form.
I go through the first array, and check the variable against a table which contains the ingredients for my website. I want to get the id of a ingredient which was added some steps before and add it into another table.
The problem is that neither the echos or the query are working.
What am I missing?
Please don't get confused by the name of the variables, I'm german :)
Best regards

Script to update mysql not working

Okay so I have a PHP script that makes a user an artist if vote is high enough. The first part of the script works (the part that does the voting). However, the second part of the script that makes a user an artist does not. It worked before on localhost but is not working on live server for some reason. Either the script has changed and I didn't notice it or there's something wrong with my server config.
I know I should be using mysqli but please don't mention that I am working on it.
To explain how the system works, a form on the voting page is posted to this script and it all runs from there.
There is no error in the error log. Updating the table for //make an artist if vote high enough just doesn't work.
Here's the script:
<?php
session_start();
include("../database.php");
$username = $_SESSION["username"];
$artistname = htmlspecialchars(mysql_real_escape_string($_POST['artistname']));
$trackname = htmlspecialchars(mysql_real_escape_string($_POST['trackname']));
$trackurl = htmlspecialchars(mysql_real_escape_string($_POST['trackurl']));
$flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload.
if(isset($_POST['yes'])){
//code runs if vote is yes
//check if user hasnt already voted on track
$result = mysql_query("SELECT username FROM voted WHERE voted='$artistname' AND trackname='$trackname' AND username='$username'")or die(mysql_error());
$check2 = mysql_num_rows($result);
if ($check2 != 0) {
echo('<t1>Sorry, you have already voted on this track. <b>Click next track.</b> </t1>');
$flag = $flag + 1;
}
//code runs if everything is okay
if($flag == 0){
mysql_query("UPDATE members SET vote = vote+1 WHERE artistname='$artistname'
");
echo '<t1><b>You liked the track "'.$trackname.'" by "'.$artistname.'"</t1></b>';
mysql_query("INSERT INTO voted (username, voted,trackname, yesno)
VALUES ('".$username."','".$artistname."','".$trackname."', 'yes')")
or die(mysql_error());
//make an artist if vote high enough
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
if ($vote > 50) {
$artisturl = htmlspecialchars(mysql_real_escape_string(str_replace(' ', '',$_POST['artistname'])));
mysql_query("UPDATE members SET artist='Y', image1='../files/noprofile.jpg', artisturl='$artisturl' WHERE artistname='$artistname'
")or die(mysql_error());
mysql_query("UPDATE tracks SET artist='Y', artisturl='$artisturl' WHERE artistname='$artistname'
")or die(mysql_error());
//email user that has just been made artist
$result = mysql_query("SELECT * FROM members WHERE artistname= '$artistname'");
while($row = mysql_fetch_array($result)){
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($row['email'], FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($row['email'], FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
{//send email
$to = $row['email'];
$subject = "Congratulations! You're now an NBS artist";
$message = "Hi ".$row['artistname'].",
//message removed for condensed code
$from = "";
$headers = 'From:' . "\r\n" .
'Reply-To: ' . "\r\n";
mail($to,$subject,$message,$headers);
}
}
echo '<br><t1>You just made "'.$artistname.'" an artist! <b>Click here</b> to see their profile.</t1>';
}
}
}
You are missing two lines to convert the resource returned by mysql_query() into an integer for the comparison with 50.
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
// Add these two lines
$vote = mysql_fetch_assoc($vote);
$vote = $vote['vote'];
if ($vote > 50) {
...however, all that section could be re-written to use 2 queries instead of 4:
//make an artist if vote high enough
$artisturl = mysql_real_escape_string(htmlspecialchars(str_replace(' ', '',$_POST['artistname'])));
// This effectively combines the first SELECT and the two UPDATEs into one query
$result = mysql_query("
UPDATE members m
LEFT JOIN tracks t ON m.artistname = t.artistname
SET
m.artist = 'Y',
t.artist = 'Y',
m.image1 = '../files/noprofile.jpg',
m.artisturl = '$artisturl',
t.artisturl = '$artisturl'
WHERE m.artistname = '$artistname' AND m.vote > 50
") or die(mysql_error());
// If this affected more than 0 rows, the user was made an artist
if (mysql_affected_rows($result) > 0) {
//email user that has just been made artist
$result = mysql_query("SELECT * FROM members WHERE artistname= '$artistname'");
// ...and so on
Note also that you should pass data through mysql_real_escape_string() as the last operation. So it should go mysql_real_escape_string(htmlspecialchars($data)) rather than the other way around.
I'll throw a dart at this one.
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
if ($vote > 50) {
I don't believe you are converting your mysql_query result into a useful variable. Maybe you were using mysql_fetch_assoc or mysql_num_rows ? Num rows makes more sense if you have an individual record for each vote. If you are summing them up then you can use something like
$output = mysql_fetch_assoc(mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
$vote = $output['vote'];
Something else to point out is that you aren't using mysql_real_escape_string on your inputs. This is very dangerous and it is strongly encouraged to use this function if you are facing the public internet.

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