Use PHPMyAdmin to manage table relationship and add data - php

I am a total newbie for php and mysql. Now I want to create a simple website for practice. I have created two tables named user_info and acct_info.
The primary key for user_info is the user_id. There is another user_id in acct_info as well.
I have relate these two tables by linking the user_id (referenced key is the user_id in user_info, that of acct_info is foreign key). However, when new user register new account on my website, new data will be added into the user_info table, but nothing happened in acct_info table.
Could anyone provide me some advice?
Sorry for not stating the problem clearly.
I have created a new user, however, data is added into user_info table but nothing in acct_info table. I thought if I build relationship between these two tables, for example, I create new user, then data like user_id and all those default data should be also added into acct_info table. I wrote php codes in my registration page to add user information into user_info table but I didn't do it to add data into acct_table. If I need to write codes for acct_table, what is the purpose to relate these two tables?
Sorry for asking dummy questions... :)
This is the php code for the data adding part:
if($reachByPOST && $okay == true && $NotExistingUsername == true && $NotExistingEmail == true) {
$sql = "INSERT INTO user_info SET user_id = '',user_name = '".$_POST['username']."',password = '".$_POST['password']."',email = '".$_POST['email']."'";
$res = mysql_query($sql);
$_SESSION['user_id'] = $userid;
$sql2 = "INSERT INTO acct_info SET user_id = '".$userid."'";
$res2 = mysql_query($sql2);
}
However, I got error saying $userid is undifiend...I just have no idea on how to add data into acct_info table...By the way the user_id is auto_increment in user_info table, it is generated automatically, not post input by user.

if you insert in user_info, it has no affect to acct_info.
But if you insert into acct_info, there should exist user_id in user_info(pri key), which will be inserted in acct_info.
Try to insert random data in acct_info.... If you don't have right user_id, you should get error.

Related

MySQLi find and delete all data for a user ID which no longer exists

My database set up may become cluttered with data from old users due to there being so many different tables which contain user information.
I am looking to run a cron job which will search ap_users (the main user table) for user_id and then use that information to check all other tables for any user_id which does not exist in the ap_users table and delete/remove those records.
I am wondering what would be the quickest and most efficient way of doing this? As I am unsure on how to check for a user_id which doesn't exist?
I have attempted something like this which doesn't seem to work, once I can get this working, I can progress it to the rest of the database:
$mysqli_find = mysqli_query($conn, "SELECT * FROM ap_user_points WHERE user_id NOT IN (SELECT user_id FROM ap_users group by user_id)");
while ($found_rows = mysqli_fetch_array($mysqli_find)){
$user_id = $found_rows['user_id'];
echo $user_id;
}

Associate a database row with a logged in user

I am currently creating a website through Joomla (creating a module) that is a members only site.
When members log in, I would want them to see their points (think about it like an airline flyer points site) which are unique. I have stored the points in a table in the database.
I have two tables:
#__users (the basic user table)
#__smiles_users (this stores the username, points etc etc)
Both tables have one similar column and this is "username".
I thought it would be wise to do it like this in an MYSQL query.
Connect to MYSQL
Find out the username that is logged in through #__users
Find the matching username in #__smiles_users table
Echo results that are in that specific row (that contains the correct username)
I have connected to MYSQL, echo the results, but I had to specify the WHERE function.
There are two main approaches to accomplish this:
You can perform two separate queries for every table and join them via a PHP associative array:
SELECT * FROM `__users` WHERE `username` = ?
And store the result to a var:
$user = $result->fetch();
Then do a second query for the remaining data of such user:
SELECT * FROM `__simles_users` WHERE `username` = ?
And join the data programatically like this:
$user_smiles_data = $result->fetch();
foreach($user_smiles_data as $key => $value) {
$user[$key] = $value;
}
Or something like this if you don't want to perform two different queries:
SELECT * FROM `__users`
INNER JOIN `__smiles_users`
ON `__users`.`username` = `__smiles_users`.`username`
This merges both tables by the username field at query time. The result will include all the fields of the two tables on a single row for the same username.
You are probably going to want to create a foreign key from one table to the other.
For example in SQL:
ALTER TABLE #__smiles_users
ADD FOREIGN KEY (username)
REFERENCES #__users(username)
This creates a link from one table to the other to ensure data integrity.

How to send data to two tables with same user ID as primary key?

I am totally new to PHP and I'm trying to create a registration page. To register, a user has to create a username, password, email, which are put into a table called users.
They also enter address details which is put into a table called customer_info.
In both tables I have created an auto increment, primary key called 'user_id'.
When the form is completed it fills out and enters the data, but the data is not banded and so there are two user_id, one in users and one in customer_info.
First I create values (from the post) that have been entered and assign them to variables. Then I put the variables into my table using the following query:
$result = mysql_query(
"INSERT INTO `users`(username, password, email) VALUES ('$value1', '$value2','$value3')"
);
and
$result = mysql_query(
"INSERT INTO `customer_info`(firstname, lastname, b_add_num, b_add_road, b_add_town, b_add_pc, p_add_num, p_add_road, p_add_town, p_add_pc) VALUES ('$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13')"
);
How would I set it so that it creates only one user id for both tables (making a connection between the sets of data)?
Is there something missing in my query, that should connect the tables?
Before anything, you should not use mysql_* extension anymore. Go towards PDO or mysqli
Your technique generates two different unique ids. The point is to have only one, so that it can be unique, and link information on that unique id.
The users table is the one with that unique id, user_id, which is your auto_increment column. The customer_info table can also have a info_id unique column, but must contain a user_id column, which will contain the user's user_id, linking the rows together.
It would also be a great moment to add a foreign key to your tables so that integrity of the data won't be compromised.
so after this query:
$result = mysql_query(
"INSERT INTO `users`(username, password, email) VALUES ('$value1', '$value2','$value3')"
);
get the insert id:
$id = mysql_insert_id();
then run your other query with it:
$result = mysql_query(
"INSERT INTO `customer_info`(user_id,firstname, lastname, b_add_num, b_add_road, b_add_town, b_add_pc, p_add_num, p_add_road, p_add_town, p_add_pc) VALUES ('$id','$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13')"
);
I would configure USER_ID as an AUTO_INCREMENT column only in Users table, insert the data into Users table first, then get the ID of the user inserted, using the mysql_insert_id ($connection_id); and use that while inserting data into Customer_Info table. This way, you can leverage the ID generation (sequence) feature of MySQL as well.

Likes Button from phpacademy

I have been working on the header recently. Now I'm end up to create some likes button like Facebook do.
I'm following the PHPacademy on Youtube. The one who's called Alex is really awesome to share what his idea is.
The problem is, I can't show the user name and the product name which to be liked
This is my query:
function plus_the_like($meal_id) {
$meal_id = (int)$meal_id;
$user_name = mysql_query("SELECT `fullname` FROM `users` WHERE `user_id` = (".$_SESSION['user_id'].")");
mysql_query("UPDATE `meal` SET `likes_meter` = `likes_meter` + 1 WHERE `meal_id` = $meal_id");
mysql_query("INSERT INTO `likes` (`user_id`,`user_name`, `meal_id`) VALUES (".$_SESSION['user_id'].", $user_name, $meal_id)") or die(mysql_error());
}
I know what I am doing wrong just on my query, but ahh... When I'm using the SQL in MySQL all works so well:
SELECT `fullname` FROM `users` WHERE `user_id` = 1
And that query can show me what is the username with the user_id 1
I hope that I can put that username from users table into likes table
Here is what you should be doing.
You have a users table with the following information
id - this is a unique ID of the user, this should be marked as a primary key. Auto incrementing.
Keep whatever else information you want on the user, possibly name, email, etc.
You have an articles table (or whatever your likes are based off of.
id - this is a unique ID of the article, this should be marked as a primary key. Auto incrementing.
Store whatever information you want on your articles, or your items in a store or whatever it is you want to "like".
You have a likes table.
id - this is a unique ID of the like, this should be marked as a primary key. Auto incrementing.
user_id - this is a unique ID of your user that clicked the like button, should be marked as a foreign key.
article_id - this is a unique ID of your article that was "liked", should be marked as a foreign key.
With this, whenever a user "likes" an article, you would have a query like
INSERT INTO likes (user_id, article_id) VALUES (:userID, :articleID);
and to count the number of likes on a given article, you would do something like
SELECT count (user_id) FROM likes WHERE article_id = :articleID;
This will allow you to track how many likes for each article, as well as what each user liked. Potentially, you could eventually suggest things to users based on what they have liked. Though, that is a lot more work to do.
This is a very basic version of what you are attempting to accomplish. As people in the comments have said, look into properly sanitizing your database input. If nothing else, at least change to my_sqli_* if you do not have PDO access. PDO is the suggested way to go though, if you are not going to use a framework that gives you all of this.

Database normalization and lazy development

I believe the question have emerged as my irritation of doing twice as much work as I could imagine is necessary.
I accept the idea that I could be lacking experience with both MySQL and PHP to think of a simpler solution.
My issue is that I have several tables (and I'd might be adding more) and of these is a parent table, only containing two fields - an id (int) and a name identifying it.
At this moment, I have seven tables with at least 15 fields in each one. Every table has a field, containing the id which I can link to the parent table.
All of these data isn't required to be filled - you will just have to create that one entry in the parent table. For the other tables, I have separate forms.
Now, these forms are made for updating the data in the fields, which means I have to pull out the data from the table if any data is available.
What I would like to do is when I receive the data from my form, I could just use an UPDATE query in my model. But if the table I want to update doesn't have an entry for that specific id, I need to do an insert.
So, my current pseudo code is like this:
$sql = "SELECT id FROM table_x WHERE parent_id = ".$parent_id;
$res = $mysql_query($sql);
if( mysql_num_rows($res) == 1 )
{
$sql = "UPDATE table_x SET ... WHERE parent_id = ".$parent_id;
}
else
{
$sql = "INSERT INTO table_x VALUES ( ... )";
}
mysql_query($sql);
I have two do this for every table I have - can I do something different or smarter or is this just the way it has to be done? Cause this seems very inefficient to me.
Use
INSERT ... ON DUPLICATE KEY UPDATE Syntax
It will insert if record not found,
otherwise, it will update existing record,
and you can skip the check before insert - details
This assuming relation for each 7 table to the parent table is 1:1
Or use REPLACE instead of INSERT - it's an insert, but will do an DELETE and then INSERT when a unique key (such as the primary key) is violated.
in mysql you can do this:
INSERT INTO table
(
col1,
col2
) VALUES(
'val1',
'val2'
) ON DUPLICATE KEY UPDATE table SET
col2 = 'val2'
take a look at the documentation for more information
mysql_query("UPDATE table table_x ..... WHERE parent_id=".$parent_id);
if (mysql_affected_rows()==0) {
mysql_query("INSERT INTO .....");
}

Categories