does changing table in MySQL affect php page? - php

I have php page that will track user on log in and store the information in table named 'logins' on phpmyadmin
now the php code for that looks like this
$numlogin = mysql_num_rows($get_client);
if($numlogin==1) {
$thisid = mysql_result($get_client,0,"id");
$thisfore = mysql_result($get_client,0,"forename");
$thissur = mysql_result($get_client,0,"surname");
$thiscomp = mysql_result($get_client,0,"companyname");
$ip = $_SERVER['REMOTE_ADDR'];
$logdate = date('Y-m-d H:i:s');
$logyear = date('Y');
$logmonth = date('m');
$logqtr = ceil($logmonth/3);
$reslog = mysql_query("insert into logins values ('','$myid','$loginemail','$thisfore','$thissur','$thiscomp',
'$ip','$logdate','$logyear','$logmonth','$logqtr')") or die("Error 91");
but if I want to add ipinfo to track their location then I have to add new column to table to store iplocation
What should I do?
Can I alter table on phpmyadmin and write some code to php later?
or what is the correct way to do?

No, you can't safely add a new column to the logins table with the code you've written. Your INSERT statement doesn't list the columns that it's inserting into, so that means you have to provide values for all the columns. If you change the table columns, the query will get an error because the number of values doesn't match the number of columns.
This is why you should always be explicit in your INSERT queries. Change it to:
$reslog = mysql_query("insert into logins (id, userid, email, forname, surname, comp, ip, logdate, logyear, logmonth, logqtr)
values ('','$myid','$loginemail','$thisfore','$thissur','$thiscomp',
'$ip','$logdate','$logyear','$logmonth','$logqtr')") or die("Error 91");
Of course, replace the column names I used with the actual column names of your table.
Once you've done this you should be able to add new columns to the table without causing the code to get an error.

Related

How can I make this sql request work in my php?

I'm trying to make a tracking system on my website that's very basic, with just the amount of people present recorded.
Unfortunately, the code below doesn't work. I checked the error logs in my server and basically here's the issue : After the first execute there are no entities found, even though there is already an entry with that value, and so the code goes straight to the "else" and then crashes because there is already an entry with that primary key. Can someone help me find why it doesn't find the entity on the first execute?
Here is the code :
$q = "SELECT date, amount FROM tracking WHERE date = ?";
$req = $bdd->prepare($q);
$req->execute(date("Y-m-d"));
$results = $req->fetchAll();
if (count($results) != 0){
$results["amount"] = $results["amount"] + 1;
$track = $bdd->prepare("UPDATE tracking SET amount = ? WHERE DATE(date) = ?");
$track->execute(array($results["amount"], date("Y-m-d")));
exit;
}
else{
$q = 'INSERT INTO tracking (date, amount) VALUES (:val1, :val2)';
$req = $bdd->prepare($q);
$req->execute(
[
"val1" => date(Y-m-d),
"val2" => 1,
]
);
}
Thanks
It looks like your tracking table must only have one row per date. There's a way to handle that directly in MySQL's query language.
First, make your date column the primary key of your table, or create a unique index on it. You create the unique index like this.
CREATE UNIQUE INDEX trackdate ON tracking(date);
Then use this single query to do your insertion / update.
INSERT INTO tracking (date, amount) VALUES (CURDATE(), 1)
ON DUPLICATE KEY UPDATE amount = amount + 1;
Each time you run this query it will either insert the necessary row, or increment the amount column. And it does it "atomically," meaning that if two different php program instances try to do it concurrently, it won't get confused.

Selecting a row where date=NOW()?

I am trying to create a table that logs steps depending on date and the user id. But when I run my code, it happens that I get duplicate rows if a user logs their steps several times a day. I can't have a date with a unique key because that would cause all other users unable to log steps if a any other user has logged steps the same day. So my point is that I want to remove the option of having duplicate rows where user id and date is identical. I have two tables
Table a and table b, and I will refer to them as something.a and something.b
I have a problem with returning a valid row when using $entry = "SELECT * FROM table.a WHERE userid.a = '$user_id.b' AND date=NOW()"
I want to use it as a conditional to decide to either UPDATE or INSERT INTO table.a. I have user_id.b from an previous query which works as it is, so I will leave that as it is for now.
Here is how I query the database:
$entry_result = mysqli_query($conn, $entry);
Which is used here:
if (mysqli_num_rows($entry_result) > 0){
$conn->query("UPDATE steplogger SET steps='$steps' WHERE userid='$user_id' AND date=NOW()");
} else {
$conn->query("UPDATE users SET totalsteps = totalsteps + ('$steps') WHERE username = '$user'");
$conn->query("INSERT INTO steplogger (steps, userid, date) VALUES ('$steps', '$user_id', NOW())");
}
Any thoughts on what I am doing wrong?
PS. When I echo $entry_result I get a mysqli object.
As you said :
I want to remove the option of having duplicate rows where user id and date
The best way is to create an UNIQUE index on user_id and date, this way you won't be able to insert two rows with same user_id and date.
With an UNIQUE index, you can use INSERT...ON DUPLICATE KEY UPDATE that will do what you want : you will insert a new row (new user_id + date) and if a row already exists with the same user_id and date, you will update the row.
Here is the documentation : https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
You can try like this
if (mysqli_num_rows($entry_result) > 0){
$conn->query("UPDATE steplogger SET steps='$steps' WHERE userid='$user_id' AND date=".NOW().")";
} else {
$conn->query("UPDATE users SET totalsteps = totalsteps + ('$steps') WHERE username = '$user'");
$conn->query("INSERT INTO steplogger (steps, userid, date) VALUES ('$steps', '$user_id', ".NOW()."))";
}
To get current date in NOW() function, you can use this function.
And also format of the two conditions should be same.

INSERT INTO SELECT with VALUES in one query

Bit new to MYSQL and PHP - I have the following code that will create a new record in multiple tables that I have setup however I need to merge the following code together somehow as it creates separate rows instead of one record
$sql .=("INSERT INTO orders (customer_id) SELECT customer_id FROM
customer_details;");
foreach($result as $item){
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$sql .=("INSERT INTO orders(product_description, delivery_mode, course_cost) VALUES('$mysql_desc', '$mysql_mode', '$mysql_cost');");
}
The result I'm getting:
Based on your data I assume that you want to insert the customer id and the values from php into the same record. In this case you need to combine them into the same insert ... select ... statement:
$sql .=("INSERT INTO orders(customer_id, product_description, delivery_mode, course_cost) select customer_id, '$mysql_desc', '$mysql_mode', '$mysql_cost' from customer_details;");
Couple of things to note:
This insert ... select ... statement will insert the same records for all customers in the customer details table. I'm not sure if this is your ultimate goal.
Pls consider the advices made in the comments regarding the old mysql API and the use of prepared statements.
To put this more into what I would expect to happen, something along the lines of - prepare statement, then loop through each item and add in new row...
$insert = $connection->prepare("INSERT INTO orders (customer_id,product_description, delivery_mode, course_cost)
VALUES (?,?,?,?)");
foreach($result as $item){
$customerID = 1; // Have to ensure this is what your after
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$insert->execute([customerID,mysql_desc,mysql_mode,mysql_cost]);
}

Selecting multiple data from a table and inserting into another table using PHP form

I've created a form that submits data into multiple tables. My fields are First Name, Last Name, Email, City/Region/Country and they're all inserted into 3 different tables (User, Email, Location).
The data goes into User and Email just fine, but I'm confused about what to do with Location.
I have 3 separate tables for Location (City, Region, Country). What I want to do is insert CityID, RegionID, and CountryID into the Location table. I have the City/Region/Country field set up so it autocompletes based on the city like this:
My Cities table has all the necessary info (CityID, RegionID, CountryID). How can I pull that data from the Cities table and insert it into my Location table?
Here's part of my code. I'm very very new to PHP and MySQL, so I apologize for the sloppiness of this. The first part of the code works, but the 2nd part doesn't (inserting data into the Location table).
//Insert static values into people table
$sql_user = sprintf("INSERT INTO User (FirstName, LastName,) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['FirstName']),
mysql_real_escape_string($_POST['LastName']),
$result_user = $db->query($sql_user);
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Insert values into location table
$sql_city = sprintf("INSERT INTO Location (UserID, CityID, RegionID, CountryID)
VALUES ('$inserted_user_id',(SELECT CityID, RegionID, CountryID, FROM Cities))");
$result_city = $db->query($sql_city);
I figure maybe I need to have "WHERE..." after FROM Cities, but I don't know what my condition would be.
That condition is up to you. If you're taking the value from the input box, it looks like you need to figure out the best way to read the location from the input field. Taking it as is you might want to first break the input into an array:
$location = explode(',',$_POST['location'])
$city = $location[0];
$region = $location[1];
$country = $location[2];
Now in your query -
"...WHERE city_name = '{$city}' AND region_name = '{$region_name}' AND country_name = '{$country}'";
*EDIT
To be more detailed, you need to setup a separate query to get the location by using SQL Joins. Your join combined with the WHERE constraints should return the city you are looking for. So here:
"SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1"
**UPDATE
This is pretty basic stuff that you can get by looking at the PHP manual on MySQL.
http://php.net/manual/en/function.mysql-query.php
Since you're new, I will grant you a pass.
After you run your this query:
$location_result = mysql_query("SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{$city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1");
You need to access the result. So:
while ($row = mysql_fetch_assoc($location_result)) {
$cityID = $location_result['CityID'];
//etc... for each associative column
}
And then in your insert query, insert the $cityID variable for CityID column, etc...

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

Categories