mySQL Update user information save null - php

I'm really not sure where to start for this one. I have researched code for days and can't really seem to find anything that plugs into the code I already have.
I feel like what I'm wanting to do is very basic; Allow a user to update a profile field by deleting it's contents and saving it as a blank value. Therefore, when it's blank, I have another code that chooses not to display that particular information if it's blank.
At this point, the field starts blank and stays blank if they leave it blank at registration but if at any point they save some information, information is always there. If you delete it and update the profile, the same information that you deleted still shows up.
I have a few files that are working together so I am having a hard time narrowing down the portion of code I need to edit to allow nulls to save. I have found what looks like a universal function to update fields - it is NOT specific to any one field (fname, lname, email, etc.).
function updateUserField($username, $field, $value){
$q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
return mysql_query($q, $this->connection); }
I would assume this is the portion of code I would need to edit to allow fields to be saved even if they are blank but I am not sure what format of:
if (empty
to place and how it gets placed in this particular snippet of code.

you can make it easy by using "" (blank string) instead of using NULL to display an empty cell in the db. By this, you are overwriting the browser forms cache and no other actions are required when displaying the content (fe a check if it's a NULL or not... ).
When handling the form data, the $_POST["field"] will return a "" if this field didn't got filled with data.
Also, you can reduce the data traffic by grouping your queries in one. Here below is an example, if you have three fields.
$q = "UPDATE ".TBL_USERS." SET ".$field_1." = '$value1', ".$field_2." = '$value2', ".$field_3." = '$value3' WHERE username = '$username'";
Or use an array and pass it to the function with the above query.

Related

mysql - Query to display record just added

I have two pages. One is a form that I use to simply input data that will be sent to my database and the second page that actually takes the data inputted into the form and sends it to the database and is supposed to display the information that I've just added.
Everything works fine, however I'm struggling with the query slightly. What I need it to do is display all the information for the last data inputted to the database.
The query I currently have just displays the data with the highest ID:
$sql = "SELECT * FROM Results ORDER BY ID DESC LIMIT 1";
So as an example I would be left with the following information after completing my form:
Success! Data being saved:
ID = 900 Amount = 206 Date = 2016-12-26
This is obviously just showing the data with the highest ID, but since the ID and all the data fluctuates, I need it to just show the data that has just been inputted.
I came accross this: Query to select newly added records only. But I don't believe this soultion to be viable as the database is external and I don't want to be creating new tables.
I was thinking that it might be possible to assign a hidden value to each newly added record via the query. e.g. New 1, New 2, New 3 etc. Then printing the latest record for New. However, I couldn't find anything on how to do this.
Any help would be greatly appreciated!
You must use this method to have very correct value:
Input form must send to another file that do inserting (we call it here insert.php)
insert.php must insert the data after validation and after that you can fetch the last ID number from database. Depending on the method you are working with it can be different. for example if you are using PDO you can get it by PDO::lastInsertId
after getting the ID you need to forward it to the viewing or editing page. for example view.php?id=LastInsertId. This forward have some reasons:
Codes can be cleaner.
We prevent refresh and resend inserting. for example if you do inserting inside view.php and user hit F5 to refresh the page, The insertion happening again.
This is the whole idea. you can use this method for only one page:
page.php?do=new
page.php?do=insert
forward to the page.php?do=view&id=lastInsertID
why you trying to get just inputted data from database? you can do it using HTTP POST/GET method easily.just send data as parameters and show them in second page.
If you already have the data you are inserting, you don't need to run a query to get it back from the database again, you could just ensure that the query was successful and display the data directly. Anyways:
You can get the insert ID from the last insert using the MySQLi object. For example:
$sql = "<your insert statement>"
$conn->query($sql);
$last_id = $conn->insert_id; //Id of the row you just inserted
$sql = "SELECT * FROM Results WHERE id=$last_id";
This is assuming you do the insert in the same page that you display the result.

Allow user that created entry to modify it only

I have been googling for some time now with out success primarily because the way i am asking is most probably the wrong way.
What i want to know
I have made some PHP scripts that allow users to add data to a table (In a MYSQL datanase) and its displayed on a website, now i am working on the ability to edit and delete the entry however the script i have allow anyone to do this to anyone's entry's.
Now i don't know if there are PHP or Mysql functions that help with this, like i said my goggling has been in vain. So if i could be pointed to a webpage that has this information or better yet an example syntax chunk that will only allow the user that created the entry to modify the entry.
I am assuming there is some type of while or if statement to achieve this.
Example scenario
A user comes along adds an entry the entry is given an id can the user be linked to that id so only he can edit it ?.
Note
I am adding PHP to a word press site so as for the users login information a word press widget is controlling that however i can see the entries are still put in a database field when I'm strolling threw the databases.
What i am asking
Do you know of a webpage/example syntax or tutorial that will show me what i need to know or if ya got enough time explain it to me :).
Thanks
Ben
Update the new entry with the current user's id, where $entry_id is the ID of the new entry
$current_user_id = get_current_user_id(); // current user logged into WordPress
mysql_query("UPDATE `table` SET `user_id`='$current_user_id' WHERE `id`='$entry_id'") or die(mysql_error());
UPDATE: You could also insert the entry with the user_id at the same time with the rest of the data.
mysql_query("INSERT INTO `table` ([other column names], `user_id`) VALUES ([other values], '$current_user_id')") or die(mysql_error());
Check if the current user ID is equivalent to the allowed edit user ID in your database.
$query = mysql_query("SELECT * FROM `table` WHERE `id`='$entry_id' LIMIT 1") or die(mysql_error());
$data = mysql_fetch_array($query);
$allowed_user_edit_id = $data['user_id']; // user id who is allowed to edit
$current_user_id = get_current_user_id(); // current user logged into WordPress
if ($current_user_id == $allowed_user_edit_id) {
// Your code for editing the entry
}

How to create a Profile URL for a user using $_GET['id']

Can someone advise me if I am performing the below steps correctly:
When a user wants to register on the website, register.php handles his/her request. Below is some of the code from register.php:
$sql="INSERT INTO Members (fldFullName, fldEmail, Password, Gender, DOB)
VALUES
('$fname','$email','$pass', '$gender', '$date')";
Particularly when I wrote the above code, I was somewhat new to PHP/MySQL and still am. Therefore, I made all of the fields above manually in the table via phpmyadmin. Furthermore, I also added the ID field manually via phpmyadmin, as the first field with auto increment and primary key of course. Why I did it manually, I can't remember the reason of. But I'm pretty sure that this may be the reason why I'm having problems.
What I'm trying to do is, when a user registers on the website, I want a profile URL to be created for him/her. For example, the field in the table could be named ProfileURL, whereas the actual value could be http://www.domain.com/profile.php?id=1, where the id is inherited from the actual ID in the table. How can I do this with my above code? Did I do something wrong when I decided to save all the fields manually via phpmyadmin? Note: I've also been creating tables, databases, fields manually via phpmyadmin. However, its values are INSERTed automatically of course. Am I even on the right track?
Thank you.
As stated above, you don't need to save a profile URL to the database. I'm guessing all profile URLs are going to follow some standard form (i.e. www.example.com/profile.php?id=1)?
Well, if you saved all of those in your database and then you decided you were going to change the format to something like www.example.com/profile/1 you're going to have a lot of out-of-date data in your database. You're going to have to go through each record and update it, and that could be dangerous on a database table with say, millions of rows.
Therefore, the solution is to have a script that takes a parameter. Say profile.php. As above, you would check for the profile using the data in the $_GET array:
<?php
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM members WHERE id = '$id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows() > 0) {
$member = mysql_fetch_object($res);
// handle displaying of member's profile here
}
else {
// member does not exist with ID
}
}
?>
That way, if you decide to change the script name or use search engine-friendly URLs, you don't need to change your database structure.
In profile.php, check for $_GET['id'], then if it exists, use a SELECT query for the same ID in the database. It would look something like this.
<?php
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM Members WHERE ID = ' . $id;
// Then the rest of the code to check the results goes here
}
?>
A user with an ID of 1 would be profile.php?id=1
You are doing right. Now write SQL like this:
$sql = sprintf("SELECT * FROM Members WHERE ID=%d", mysql_real_escape_string($_GET['id']));
And you'll be able to get userdata by $_GET['id']. Remember to use mysql_real_escape_string to protect your queries against SQL injection. sprintf is also a good thing to substitute right data types like numbers or strings.
You don't heed to save profile url.
You have to build it dynamically.
Because most of the url remains the samy, only id is changing.
So, get id from the database and add it to the url.

Setting multiple fields in a database, from just one field

I am working in the confines of a CMS system, which defines certain fields which can be used to make forms for use within the application in PHP.
I am making use of the inputSmartSearch field, which is basically similar to Google suggest.
It allows me to define an SQL query, and then displays records that match as I type in my search.
For my smartsearch, I have chosen it to search through three fields in a different table, and to display those fields concatenated together.
I use define my field like so:
$theinput = new inputSmartSearch($db, "chooseguests", "Choose Guests");
The last parameter is the name of the SQL query to execute.
This works fine, and a guest can be located by searching his last or first name.
However, I have implemented this smartsearch what is meant to be the page to add a sales order.
In each sales order stored in the sales table, distinct from the guest table, I also want to have the firstname and lastname of the guest making the order.
The design of the sales order table has two separate fields for firstname and lastname.
Using smartsearch, I cannot find any way to tokenize the selected input and insert it back into the field.
If I have a smartsearch and can search by firstname or lastname it shows the result as just one fields, and I want it to save the firstname to the firstname field and the lastname to the lastname field.
Each form defined has an include file which defines the function for inserting a record and such, like so:
function prepareVariables($variables){
// if ($variables["webaddress"]=="http://")
// $variables["webaddress"] = NULL;
return $variables;
}
function updateRecord($variables, $modifiedby = NULL, $useUuid = false){
$variables = $this->prepareVariables($variables);
return parent::updateRecord($variables, $modifiedby, $useUuid);
}
function insertRecord($variables, $createdby = NULL, $overrideID = false, $replace = false, $useUuid = false){
$variables = $this->prepareVariables($variables);
return parent::insertRecord($variables, $createdby, $overrideID, $replace, $useUuid);
}
However, I am unsure of how I could modify the insert or update functions to do what I need them to do, or if that is even the correct approach.
Should I be looking for a complex sql query? hidden fields with the content autopopulated from the result of my inputSmartSearch? Something else?
Not sure what's possible with the setup you've got going, but... my first reaction would be to return from the db the names combined with tokens - like - ',' So Smith, John. Then, when getting ready to send back, to split those up ( based upon the known token ). Now where that goes what you've got there, I do not know.
You just need to set the starting value of the smart search manually using the values from the database. Then when the data is posted to the server you can parse and append to the array that is used to store the data in the database. At least that seems like it should work.

PHP mySQL database check

I am having endless troubles with duplicate entries, so I need to check the database, and if a user has already entered that day, their entry will not be submitted and they will be redirected to a landing page that tells them they have already entered that day, and that they may only enter again tomorrow.
The field I would like to check is the id_number field in the database, since each user has a unique id number, so basically, if a user with the same id number submitted on the same date they should be redirected to a landing page, how would I go about doing this? I am still new to a lot of this, so please be forgiving.
Thanx in advance.
before you submit your sql query to add a new record you can read the DB first to make sure the ID is not already in there. Get the users id into a variable and do this query.
$query = "select * from mytable where `id` = '$id'";
$result = mysql_query($query);
then you can count the number of records returned and do different things depending on the result, checking that its zero before adding them. If its not zero then redirect.
if(mysql_num_rows($result) > 0)
{
//add them
}
else
{
//redirect them
}
Hope this helps you out

Categories