Auto grab ID function? - php

Alright so I have two tables that I am working with.
The first is set up something like these tables
Destination
IDDestination Name IDCity IDState
1 Scottsdale 3 4
2 Miami 5 7
and
Destinations_Citites
IDDestinationCity IDDestination IDCity
1 1 3
2 2 5
Now with my plugin I have an add a new destination button which adds a new destination with its Name, IDCity and IDState filled out by the user and the IDDestination is automatically generated.
So what I want to figure out how to do is to grab that automatically generated IDDestination # and enter it into the Destinations_Cities table with out having the user do anything else.
Basically how can I insert the automatically generated IDDEstination that was just created and throw it into my other table without the user having to add it themselves.
Here is the code I am using to Insert and Update for my add destinations button
if(isset($_POST['Add_Destination'])) {
$idstate = $_POST['idstate1'];
$idcity = $_POST['idcity'];
$name = $_POST['addname'];
$SQL="INSERT INTO destination (name, IDCity, IDState) VALUES ('". $name ."','". $idcity ."','". $idstate ."')";
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
$result=mysql_query($SQL) or die (mysql_error());
$result1=mysql_query($SQL1) or die (mysql_error());
print $SQL;
print $SQL1;
}

You can get the most recent auto-increment id generated during your session:
$dest_id = mysql_insert_id();
Refer to the documentation: http://php.net/manual/en/function.mysql-insert-id.php
Not exactly about your question, but I echo the comment above that you should protect your queries from SQL injection vulnerabilities. Don't copy PHP variables into SQL strings unless you have made sure the variables are made safe.
If a variable is supposed to be an integer, use (int) to cast it to an integer as you read it.
For string values, use escaping provided by the MySQL API.
Also, there's no need to do all the . concatenation if you're just putting simple variables inside PHP strings. There's no need in SQL to put quotes around integer literals.
Here's an example:
if(isset($_POST['Add_Destination'])) {
$idstate = (int) $_POST['idstate1'];
$idcity = (int) $_POST['idcity'];
$name = mysql_real_escape_string($_POST['addname']);
$SQL="INSERT INTO destination (name, IDCity, IDState)
VALUES ('$name', $idcity, $idstate)";
$dest_id = mysql_insert_id();
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
. . .
If you convert your code to use PDO, you can use SQL query parameters, in which case you wouldn't need to worry about escaping and such.

Related

Overwrite existing score if new score is higher [duplicate]

This question already has answers here:
on duplicate key update with a condition?
(2 answers)
Closed 2 years ago.
On submitting (ID, username, score), I only want the database to update if the score is higher than the usernames previous score.
So far I have
$sql = mysqli_query($con, "INSERT INTO $db_name.$db_table (ID, name, score)
VALUES ((ID, name , score) IF $ID=ID & $name=name & '$score'>score);");
Full code is
if(isset($_GET['ID']) & isset($_GET['name']) & isset($_GET['score'])){
$con = mysqli_connect($host, $db_username, $db_password, $db_name);
$ID = strip_tags(mysqli_real_escape_string($con, $_GET['ID']));
$name = strip_tags(mysqli_real_escape_string($con, $_GET['name']));
$score = strip_tags(mysqli_real_escape_string($con, $_GET['score']));
$sql = mysqli_query($con, "INSERT INTO $db_name.$db_table (ID, name, score)
VALUES ((ID, name , score) IF $ID=ID & $name=name & '$score'>score);");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo("<br>Error description: " . mysqli_error($con));
}
mysqli_close($con);//Close off the MySQLI connection to save resources.
You seem to want on duplicate key update. You want one row per name, so you need a unique index or cosntraint on name:
CREATE UNIQUE INDEX unq_table_name ON $db_name.$db_table(name);
Then you can use:
INSERT INTO $db_name.$db_table (ID, name, score)
VALUES (ID, name, score)
ON DUPLICATE KEY UPDATE score = GREATEST(score, VALUES(score));
The use of $db_name.$db_table is highly problematic. It suggests that a single entity (whatever should be in the table) is spread through multiple tables. That is really bad data modeling.
In addition, it potentially opens the code to SQL injection and hard to debug syntax errors. I would recommend that you re-think your database design so you have scores in only one table, perhaps called user_scores or something more intelligible than $db_name.$db_table.

How to insert multiple values in a specific field in a table using mysqli? [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 7 years ago.
I am working on a project and I I have a scenario like this:
I have many field in my table :
table_name : transaction_tbl
-id
-name
-description
-ref_number : text(datatype)
In my inserting here is my code:
$sql = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`) VALUES ('$name','$desccription',$ref_number)";
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
As the name itself ref_number or reference number, so there will be a time that I will have a lot of reference number,how can I let it insert if it will have multiple values?
Thanks :)
UPDATE :
I want something like this :
name description ref_number
bag to be use 10359435846
05438547656
035848576
Its not a good practice to have multiple values in one cell (and you should never unless there is a serious reason). It violates basic db rules. Just split this to two tables and assign foreign keys to link them up.
Learn db normalization. There are lot of examples. In here you need to take your un-normalized (0NF) table to at least to 1st normalized level (1NF). But its advised to make it normalized at least up to 3rd level
google for db normalization tutorials. As you request below image will give you an idea(field names are not same as in your question).
First insert the values to table1(Member table) and get the insert id in php use $iid = mysqli_insert_id()
Next add the multiple values as seperate rows into the second table(database table) along with the primary key obtained in first step.
Keep in mind this is not a tutorial site. find more info on net.
for what purpose ? why don't you just insert a new row with the same name and description with different ref_number ?
but if you would like that , you can concatenate your new ref_number with the existing ..
first check if it already exist
get its value then concatenate the new ref number ..
or if it doesn't exist , insert a new row ..
$sql = "SELECT `ref_number` FROM `transaction_tbl`
WHERE `name`='$name' AND `description`='$description'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$new_ref = $row['ref_number'] . '|' . $ref_number;
$upd = "UPDATE `transaction_tbl` SET `ref_number`='$new_ref'
WHERE `name`='$name' AND `description`='$description'";
}
else
{
$ins = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`)
VALUES ('$name','$desccription',$ref_number)";
mysql_query($ins);
}

Last insert id value store to same table another specific column

i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";

How do I select data from my table and make it a string?

I am trying to use a database where the email can have multiple entries, but i would like to prevent duplicate entries. Currently i have:
<?php
"SELECT Notes, itemName from UserItems where email = '$email'";
if("itemName" == $name && "Notes" == $desc) {
echo "duplicate";
}
?>
But itemName and Notes need to become strings for my if statement to work
My insert function is lower in my code but ill post it
$insert = ("insert into UserItems (itemName, ItemNumber, email, Price, Notes) Value (\"$name\", \"$ItemNumber\", \"$email\", \"$price\", \"$desc\")");
Am I missing something here? I held off answering cause I thought this would be too obvious and my post would waste time -
<?php
// add actual db connection info here
$email = 'someon#somewhere.com';
$name = 'John';
$desc = 'Some Description';
$row = mysql_fetch_array(mysql_query("SELECT Notes, itemName from UserItems where email = '$email'"));
if($row['itemName'] == $name && $row['Notes'] == $desc) {
echo "duplicate";
}
?>
You never actually run a query or fetch the results. Or define the variables you're comparing against. Are they $_POST, $_GET, results of the last row or something?
What about counting the number of entries where email = '$email'?
Based off the conversation we had in the comments, it sounds like your best bet is to handle this functionality at the database layer, by adding a unique contraint across all three columns (email, itemName, notes). With this solution the database will not allow more than one row with the same value for all three columns.
The mysql command would be:
alter table <your_table> add unique (`email`, `itemName`, `notes`);
// Will be inserted/updated no problem
foo#bar.com, itemName1, notes1
foo#bar.com, itemName1, notes2
foo#bar.com, itemName2, notes1
// An error will be returned because this row already exists
foo#bar.com, itemName1, notes2
The only drawback is that writes to the database will more costly as all three columns (notes especially) will have to be considered for the unique constraint.
Your other option is to load all rows matching the email address, then step through each row searching for matches against itemname and notes, which will be even more painful.

Possible to make this code valid/speed up?

I have an enrollment form which takes consumer information, stores it in session, passes from page to page then stores in a database when finished. Originally the table simply listed fields for up to 16 persons but after reading into relational databases, found this was foolish.
I have since created a table named "members" and "managers". Each enrollment will take the information input, store the manager ID in the respective table and place a reference field in each member row containing the manager ID.
While I allow up to 16 members to be enrolled at once, this can range from 1-16.
My best guess is to use a FOR-loop to run though multiple INSERT statements in the event more than 1 member is enrolled.
In the example below, I am using the variable $num to represent the individual member's information and $total to represent the number of all members being enrolled. The code here does not function but am looking for:
a) ways to correct
b) understand if there are more 'efficient' ways of doing this type of INSERT
sample code:
<?php
$conn = mysql_connect("localhost", "username", "pw");
mysql_select_db("db",$conn);
for ($num=1; $num<=$total; $num++) {
$sql = "INSERT INTO table VALUES ('', '$clean_f'.$num.'fname', '$clean_f.$num.mi', '$clean_f.$num.lname', '$clean_f.$num.fednum', '$clean_f.$num.dob', '$clean_f.$num.ssn', '$clean_f.$num.address', '$clean_f.$num.city', '$clean_f.$num.state', '$clean_f.$num.zip', '$clean_f.$num.phone', '$clean_f.$num.email')";
$result = mysql_query($sql, $conn) or die(mysql_error());
}
mysql_close($conn);
header("Location: completed.php");
?>
If all of your statements are structurally the same, but with different parameter values, consider using the PDO extension, which supports prepared statements. The benefits of prepared statements can be read here (http://www.php.net/manual/en/pdo.prepared-statements.php), but in general, the same statement will only need to be compiled once, but can be executed as many times as you want with different parameters, which can make your script more "efficient".
Using PDO, your code could look something like:
$db = new PDO('mysql:host=localhost;dbname=db', 'username', 'pw');
$statement = $db->prepare('INSERT INTO tablename (field1, field2, field3, ...) VALUES (?,?,?,?');
for ($num=1; $num<=$total; $num++) {
$statement->execute(array('val1', 'val2', 'val3', '...'));
}
Generally, putting a query in a loop is bad thing. There is usually a better way. In this case, you should use the multi-insert syntax. Your INSERT isn't working because you didn't specify the fields. I'm assuming the lack of a space between the table name and VALUES is a typo, along with the bad quoting.
INSERT INTO table_name (field1, fname, lname, fednum, ...)
VALUES ('val1', 'Pete', 'Moss', 1234),
('val2', 'T.', 'Cupp', 54321),
('val3', 'Youdid', 'Watt', 787123);
The solution, if I read you right, is to start with the fixed query string:
$queryString = "INSERT INTO table (field1, field2, ...) VALUES ";
then run a loop to build the malleable part. Putting your values into arrays makes things easier:
$queryInsert = '';
$total = count($value1Array);
while ($i < $total) {
$queryInsert .= "('$value1Array[$i]','$value2Array[$i]','$value3Array[$i],...), ";
++$i;
}
then append to the first query piece:
$queryString = $queryString.$queryInsert;
and trim off the trailing , and you're good to go.

Categories