include("connect.php");
$username = mysql_real_escape_string($_REQUEST[username]);
function updateData($key){
$field = "$$key";
if($field == "") {
} else {
$sql= "UPDATE users SET $key = '$field' WHERE username ='$username'";
mysql_query ( $sql , $conexion );
}
}
updateData('password');
updateData('firstname');
What I'm trying to make is an automatic way for this PHP file to recognize the fields and not save them if the input field value is empty.
If I mannually put the name of the field on the $key spaces, it works, but once I turn it into a function an run it, it doesn't work.
Don't write your code like this.
For starters, it's not readable - it makes whoever is maintaining the code have to go find this function to figure out where the data being used is coming from.
Secondly, you'll run into issues with variable scope - inside the function, none of your variables are defined unless you reference them with the global keyword to bring them into scope.
Instead, write your function like this:
function updateData($username, $key, $value){
if($key != "" && $value != "") {
$sql = "UPDATE users SET $key = '$value' WHERE username ='$username'";
mysql_query($sql, $conexion);
}
}
and pass in the relevant values; that's what function arguments are designed for. You might also want to consider escaping the contents of the arguments before interpolating them.
i think the problem , its that variables $username , $sql , $conexion not recognize in this function
look on this link variables scope
Related
I have looked on here about if statements. I have found a few things but I am having issues figuring out the proper statement formula.
I have 2 tables in the database with the following 2 fields
table 1
rct_app_id
table 2
uid
now if the uid field matches the rct_app_id field I want it to
echo "Green Light";
if they don't match
echo "No Go"
this is my formula
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
$rct_app_id = ['rct_app_id'];
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
?>
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
Try this. but keep in mind its hard for people to figure out whats going on by bits and pieces and it makes it harder to help you.
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql);
while(($row = mysqli_fetch_assoc($result))!=false){
$rct_app_id = $row['rct_app_id'];
if ($rct_app_id == $user_id) {
echo "Green Light";
} else {
echo "No Go";
}
}
}
?>
You need to fix two lines. $result has the results from the database, so that's the source for the rct_app_id data. Then, when you do the comparison, you need to compare the two variables.
$rct_app_id = $result['rct_app_id'];
if ($rct_app_id == $user_id) {
The way you have it, you're comparing an array to a string.
When you do this:
$rct_app_id = ['rct_app_id'];
You're actually setting the variable $rct_app_id equal to an array with one element, although the syntax is incorrect. Instead, you need to get one element of the array that is returned from the database. This assumes that you have a function called query() that is working properly and returning an array.
Instead, we need to set the variable equal to one element of the array like so:
$rct_app_id = $result['rct_app_id'];
Then, when you do a comparison like this:
if ($rct_app_id == 'uid') {
you're saying if the variable $rct_app_id is equal to the string uid, which it's not. Variables always start with $ in php, strings are quoted. The variable set earlier in the script is $user_id (from SESSION), so we need to compare to that:
if ($rct_app_id == $user_id)
UPDATE: You've specified your sql lib, I've edited the answer below to work with your updated answer.
Since you didn't specify the library, I'm making the answer and the code edits with the assumption that you're using mysql. Though all queries and return functions use similar syntax, ie: mysql_fetch_assoc() = mysqli_fetch_assoc(), pg_fetch_assoc(postgres).
<?php
$user_id = $_SESSION['uid'];
$sql = "SELECT * FROM recruits WHERE rct_app_uid = {$user_id}";
$result = query($sql); //What type of query runs as just query()? mysql_query would go here if this was mysql. Some Libraries offer this as a function, but since you didn't specify the library, I'm going to change it to mysql_query and proceed as if you're using mysql.
//$rct_app_id = ['rct_app_id'];//This will never work.
//You need this:
while($row=mysqli_fetch_assoc($result)){
//We only expect one result
$rct_app_id=$row['rct_app_id'];
}
if ($rct_app_id == 'uid') {
echo "Green Light";
} else {
echo "No Go";
}
function query($query)
{
global $connection;
return mysqli_query($connection, $query);
}
?>
I am having a problem with passing a $query variable to a mysql_query command. So if I do this I get an update in the database (which I wanted):
$query = "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
mysql_query ($query, $db);
However, I need to use a function to do this. I'm trying to use this code, but I am no longer able to get the update to the database that I wanted:
if ( !function_exists("testQuery") ) {
function testQuery($id) {
return 'UPDATE master SET finished_size = "$finished_size" WHERE id = $id';
}
}
$query = testQuery($id);
mysql_query ($query, $db);
I have tried many ways of doing this, but the $query variable which contains the string to pass to the mysql_query function doesn't seem to be recognized. But I don't know how else to do this the proper way.
Also, I realize mysql_query is an old function, but this is the code that I have to use because I'm working on very old software.
Add another parameter to the function.
Also, variables are only expanded inside double quotes, not single quotes. See What is the difference between single-quoted and double-quoted strings in PHP?
if ( !function_exists("testQuery") ) {
function testQuery($id, $finished_size) {
return "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
}
}
$query = testQuery($id, $finished_size);
mysql_query ($query, $db);
If you're putting a variable to a string without connecting more strings, you have to use quotes, not apostrophes. So:
return "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
It turned out that the problem was that I was using $_POST variables, that had already been extracted, so that $finished_size was no longer treated as a global variable (like $_POST['finished_size'] would be). And so the extracted variable did not have scope access within the function.
So I just re-extracted $_POST inside the function. I had many $_POST variables coming in from a form, and so extracting them inside the function seems to be a fairly convenient way to pass them back to $query.
The answers that were given prior to this were helpful for me to realize that it was a scope issue.
So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more
echo $uid; // RETURNS INTEGER VALUE
if (isset ( $_POST ['cashpaid'] )) {
$queryfinal = "select * from " . $db_prefix . "customer_det
where `id` = '$uid'"; // UID RETURNS NULL
....
I've tried everything and every combination of globals and super globals that I could think of. There's just no way I can transfer the value over.
I pull $uid from a MySQL select and it assigns to an integer value. As you can see at the start of the code, that ending curly brace is the end of an IF statement which contains the value for $uid.
How can I assign the same value to $uid across all scopes?
This has been killing me for about two days. I'm sorry if this seems elementary but it's about to drive me nuts. I tried $GLOBALS['uid'] to no avail.
You could try with a setter/getter function declared once in the global scope, but it doesn't do much more than accessing GLOBALS anyway.
function globalUid($value = False)
{
GLOBAL $__uid;
if (!isset($__uid))
$__uid = False;
if (False === $value)
return $__uid;
$__uid = $value;
}
Then instead of echoing $uid, try globalUid($uid) and, later, $saved_uid = globalUid();.
But I think it's possible the two scopes are executing across two different calls, so you might need to save the UID in the session variables.
I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php