add mysql row if userID do not exist in table - php

i'm sending a post request to this code:
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
Which works fine and it adds a row to the table. How do i check wether the userID all ready exist in one of the following rows?

Do it like this
$query = "SELECT COUNT(*) FROM Users WHERE userID = '$id'";
$result = mysqli_query($link,$query);
if ( mysqli_fetch_assoc($result) ) {
$message = "Already exists";
} else {
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
}

Try this
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$res = mysqli_query($link, "SELECT * FROM Users WHERE userID = '$id' LIMIT 1 ");
if($row = mysqli_fetch_assoc($res))
{
echo "this user id is already exists";
}
else
{
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
echo "record inserted successfully ";
}
REMEMBER : always use LIMIT 1 when you trying to get exactly one result.

IF you have properly set 'id' as primary key or unique key in your table, you can use the modifier IGNORE in your query you don't get an error when you try to isert a duplicate.
Doing this will result in the row only being inserted if the value of the primary key wasn't already in the table.
$query = "INSERT IGNORE INTO Users (name, userID) VALUES ('$name', '$id')";
IF you haven't set a primary key in your table you will have to do a SELECT query to find out if a row with that id is already in your table.

Make the UserID an Unique Key.
If it already exists, your code will throw an error and the row will not be insterted.
alter table Users
add unique index Unique_user (userID (8000))

Before inserting the values to the table check whether the following user id exists in the table or not
You can do it in this way
$name = $_POST['name'];
$id = $_POST['id'];
$sql = "SELECT * FROM Users WHERE userID = '$id'";
$res= mysqli_query($sql);
$num = mysqli_num_rows($res);
if($num == 0)
{
$query2 = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result2 = mysqli_query($query2);
echo "record inserted successfully ";
}
else
{
echo "Record Failed !!";
}

Related

adding user info and log in info in different page

so I want to make a sign up where at the first page, is the user info where the name, last name etc will be input by the user, then it will be recorded into the database and redirect to the account info page where the user input the username and password and be recorded in another database so I have to tables the student, where all the info is stored, and user, where account info is stored so the userID of the user will be the foreign key of in the student but I cant put the id number of the user to the table of the student where the first input is stored in the first page, so if I use the mysqli_insert_id it can insert the id of the last inserted user into the student table but into the next row not the row where the last input of information in the first page is located
code in the first page shs/functions/add.stud.php
<?php
session_start();
include 'database.php';
if (isset($_POST['add'])) {
echo "welcome";
}
$message = "Provide all information needed please";
$lname = $_POST['Lname'];
$fname = $_POST['Fname'];
$mname = $_POST['Mname'];
$email = $_POST['email'];
$grade = $_POST['grade'];
$strand = $_POST['strand'];
$section = $_POST['section'];
$status = $_POST['status'];
if (empty($lname) || empty($mname)) {
header("Location:../pages/user.add.php?empty=put something, will ya?");
exit();
}
else {
$sql = "INSERT INTO student (lname, fname, mname, gmail, grade, track, section, status)
VALUES ('$lname', '$fname', '$mname','$email', '$grade', '$strand', '$section', '$status')";
$result = mysqli_query($conn, $sql);
}
then in the account information (username, password)
<?php
if (isset($_POST['users'])){
include_once 'database.php';
$uid = $_POST['uid'];
$pass = $_POST['pass'];
//pag check or pag handle sa mga errors sa pag log in
if (empty($uid) || empty($pass))
{
header("location:../pages/user.add.php?signup=empty fields");
exit();
} else {
$sql = "SELECT * FROM 'user' WHERE username ='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 0) {
header("Location:.../user.add.php?the inputs are already taken");
exit();
}
else {
$hashedpass = password_hash($pass, PASSWORD_DEFAULT);
//insert the new user to the user database
$sql = "INSERT INTO user (userID, username, password)
VALUES (NULL, '$uid', '$hashedpass');";
$result = mysqli_query($conn, $sql);
//pag connect sa student database
//katung sa database sa image
$sql = "SELECT * FROM user WHERE username ='$uid'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
$userid = $row['userID'];
$sql = "INSERT INTO profileimg (userID, status)
VALUES ('$userid', 1)";
if($result=mysqli_query($conn, $sql))
{
$last_id = mysqli_insert_id($conn);
$sql = "INSERT INTO student (userID) VALUES ('$last_id')";
$result = mysqli_query($conn, $sql);
}
else {
header("Location:.../user.add.php");
exit();
}
//pag add sa id sa user paingun sa student
header("Location:../pages/user.add.php");
}
}
after putting the inputs in the first page it will redirect to another page where the user must input the account info..that's the desired function
The best way is to store the User Info in the student table then use the mysqli_insert_id function to grab the studentId. Then save the Account Info in the user table and grab the userId. Thereafter update the student table with userId where studentId is the same as the one you grabbed earlier.
$sql = "INSERT INTO student (lname, fname, mname, gmail, grade, track, section, status)
VALUES ('$lname', '$fname', '$mname','$email', '$grade', '$strand', '$section', '$status')";
$result = mysqli_query($conn, $sql);
$_SESSION['studentId'] = mysqli_insert_id($conn); //add this line to store the studentId into the session.
$sql = "INSERT INTO student (userID) VALUES ('$last_id')"; // change this line to the one below.
$sql = "UPDATE student SET userID = '$last_id' WHERE studentID = $_SESSION['studentId']";

Insert INTO with 3 tables

$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id) VALUES ('','')";
I am new in php and my hint is to link 2 tables id's in in another one called users_addresses.When a user is registered in my database i want the user_id and address_id to clone in users_addresses(ua_user_id,ua_address_id)
My tables
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
These are my others SQL codes for adding session's data in DB.
Just need get user_id from first sql. If you are using mysqli function, do this
// run your first sql: insert user
mysqli_query($con, $sql);
$user_id = mysqli_insert_id($con); // or mysqli::$insert_id
Next, you have $user_id variable with user id.
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ($'{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
mysqli_query($con, $sql);
$address_id = mysqli_insert_id($con); // or mysqli::$insert_id
$sql3 = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES ($user_id, $address_id)";
mysqli_query($con, $sql);
Use mysqli_insert_id() to get the unique ID of the insert table, this example uses Procedural style:
<?php
include 'connection.php';
......
$InsertSQL = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}',
'{$_SESSION['userinfo']['mname']}',
'{$_SESSION['userinfo']['lname']}',
'{$_SESSION['userinfo']['login']}',
'{$_SESSION['userinfo']['email']}',
'{$_SESSION['userinfo']['phone']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$UserID = mysqli_insert_id($conn); // <-- get the UserID
$InsertSQL = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}',
'{$_SESSION['addressinfo']['adr2']}',
'{$_SESSION['addressinfo']['zip']}',
'{$_SESSION['addressinfo']['city']}',
'{$_SESSION['addressinfo']['provinciq']}',
'{$_SESSION['addressinfo']['durjava']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$AddressID = mysqli_insert_id($conn); // <-- get the AddressID
$InsertSQL = "INSERT INTO user_addresses (ua_user_id,ua_address_id)
VALUES ($UserID,$AddressID)"; // <-- INSERT INTO user_address
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
?>
You should also look into SQL Injection vulnerability, check out prepared statements.
Hope that helps.

(Php)Retrieve primary key of previous table and insert into current table

Im new to php scripting.. I want to know if there is any mistake in my php script that i want to fetch income_id (primary key in income table) from income table and insert it into expenses table(as foreign key)...I able to add all data into expenses table except the income_id..
<?php
//Importing our db connection script
require_once('dbConnect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$income_id = $_POST['income_id'];
$category = $_POST['category'];
$amount = $_POST['amount'];
$date = date('Y-m-d');
$sql = "SELECT income_id from `income` where id='".$id."'";
$result = mysqli_query($con, $sql);
$rows = mysqli_fetch_array($result);
//Creating an sql query
$sql = "INSERT INTO expenses (income_id,category,amount,date) VALUES ('$rows[income_id]','$category','$amount','$date')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Added Successfully';
}else{
echo 'Could Not Add';
}
//Closing the database
mysqli_close($con);
}
I would suggest joining both queries:
INSERT INTO expenses (income_id, category, amount, date)
VALUES ((SELECT income_id FROM `income` WHERE id='$id'), '$category', '$amount', '$date')

How to transfer several rows from one table to other table (SQL)

I have two tables TableA and TableB with colums id, login, pass. Also I have a php array: $array = [1,3,5]. How can I transfer rows from TableA to TableB where id equal each value of my array? id is autoincremented and must be unique.
In my head it looks like this :
INSERT INTO TableB (`login`, `pass`)
SELECT `login`, `pass` FROM TableA WHERE `id` = $array[0]
AND `id` = $array[1] AND `id` = $array[2];
But it does not work
Is there any chances to do it in cycle using WHILE?
You can use a statement such as this:
$ids = [1,3,5];
$query = "INSERT INTO `TableB` (`login`, `pass`) SELECT `login`,`pass` FROM `TableA` WHERE `id` IN (".implode(",", $ids).");";
Although: You should be using prepared statements and parameters for this, this answer is just meant to show the syntax.
it is easy let's say you are using mysqli:
$query= "SELECT * FROM TableA limit 3";
//takes first 3 rows from TableA
//$con being the connection string in config file
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
//takes each row by row
$username = $row['username'];
$password = $row['password'];
//now that we initiated variables the sql query
$query1 = "INSERT INTO TableB (username, password) VALUES ('$username', '$password')";
mysqli_query($con,$query1);
}
Hope this helps
EDIT:
I just read that it should have an array so you should change your query to this:
for($i=0; $i<count(array), $i++){
$query= "SELECT * FROM TableA WHERE ID = '$array[i]'";
//$con being the connection string in config file
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result){
//takes each row by row
$username = $row['username'];
$password = $row['password'];
//now that we initiated variables the sql query
$query1 = "INSERT INTO TableB (username, password) VALUES ('$username', '$password')";
mysqli_query($con,$query1);
}
}

Cannot insert data in SQL table when using the same code as previous query

I need to insert two pieces of data into two different tables. It successfully does it with one of the tables but not the second. I have used or die mysqli_error to see if it will tell me the error, but it does not show anything. See the code below:
$sql = "INSERT INTO ticketUsers
(name, emailAddress, password)
SELECT * FROM (SELECT '$name', '$emailAddress', '$dbPassword') AS tmp
WHERE NOT EXISTS (
SELECT name
FROM ticketUsers
WHERE emailAddress = '$emailAddress'
)
LIMIT 1";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering ticket Users";
}
else if(!$result)
{
echo "Cant enter information";
}
$sql = "INSERT INTO tickets
(id, emailAddress, urgency, subject,
description, relevantURL, status)
VALUES ('$id', '$emailAddress', '$username', '$urgency',
'$subject', '$description2', '$relevantURL', 'Open')";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering tickts";
}
else if(!$result)
{
echo "Cant enter information";
}
if (!sql)
{
echo "There has been an error creating your ticket.";
}
In your second query, you try to insert in a table with 7 fields 8 values.
I think you don't want to insert '$username' in the query.

Categories