Mysql info in select tag - php

So I've been trying to figure out how to do this but I've had no luck.
I have a database that includes ID, name, date, and username
I have a simple submit form that generates an id and a user adds a name and an event date then it logs the username, However I would like to take that date and then have it appear in a select tag with the format of Name - Date and have it sorted by the closest date. I want to view info about that event when someone clicks it. But I can't figure out how to make it appear in the select tag. I don't even know where to start with this. all help appreciated.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = uniqid(rand(), false);
$name=$_POST['name'];
$date=$_POST['date'];
$username = $_POST['username'];
// Insert data into database
$sql="INSERT INTO events (id, name, date, username)
VALUES
('$id', '$name', '$date', '$username')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
error_log(implode("-",$_POST));
$conn->close();
?>

Related

column doesnt match when its empty

How should i solve this? there is not a row 1 and i cant insert or update data. Unique keys are indeed ip and uid in my table.
My code is as follows:
//Retrive listeners per reload
echo 'Data Höganäs <br>';
$sc="http://USER:PWD#SUB.SERVER.se:10000/admin.cgi?sid=1&mode=viewxml&page=3";
$xml2 = simplexml_load_file($sc);
foreach ($xml2->LISTENERS->LISTENER as $listener2) {
// Create connection
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " insert INTO hoganaskey
(ip, uid, tid, starttid, date)
VALUES
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
on duplicate key
update tid='$listener2->CONNECTTIME' ";
//$sql = "INSERT INTO hoganaskey (ip, uid, tid, ua, starttid, date) VALUES('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT' '$starttid', '$date') ON DUPLICATE KEY UPDATE tid='$listener2->CONNECTTIME' ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} //End foreach SHOUcast listener
Im returning this error in insert "Column count doesn't match value count at row 1".
In your insert query, you listed only 5 field names:
(ip, uid, tid, starttid, date)
but you are passing 6 values not 5:
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')

Insert into two table foreign key and primary key

I have two tables in my database namely reservations and guests. The rows are as follow:
Reservation:
Reservation id
Property Id
Checkin date
Checkout date
Price
Guest
Guest id
Reservation id
Guest name
Guest address
Using a form that contains the reservation details and the guest details at the same time.
How can I run the insert query so that the auto generated reservation id(auto-increment in database) can also be inserted into the guest table at the same time?
This is what I have so far. I changed my code using last_insert_id()
INSERT INTO reservations
SET Checkin date= '24/05/2018', checkout date = '29/05/2018';
INSERT INTO guests
SET reservation id = LAST_INSERT_ID(),
guest name = guest name
First insert to reservation table
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlR = "INSERT INTO Reservation(firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
$rStatus = $conn->query($sqlR);
$res_id = $conn->insert_id;
$sql = "INSERT INTO MyGuests (firstname, lastname, email,res_id)
VALUES ('John', 'Doe', 'john#example.com',$res_id)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Firstly you can insert the data into the Reservation table, based on the last inserted id, you can use the value for the column Reservation id for the table Guest. Also, please maintain foreign key constraints, so as on update and delete operations of Reservation, simultaneous operations are performed on the Guest table.
To get the last inserted id,
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ...";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; //gives the last inserted id
}
Run the insert query first with the insert_id function and then use that insert_id to run the second insert query

(MYSQL) How to insert a record only if it doesn't exist in a table

Hi maybe this question has already been answered but nothing has been helpful.
I'm using Mysql and I want to insert some data in a table but i want to check for duplicated records before inserting .
I'm very confused about how to achieve this.
I need to check if "RFC==$Expediente AND Diagonal ==10 or Diagonal==20" and show something like "Record already Exist",
or insert all the data if record doesn't exist
this is my script :
<?php
$Person_name=$_POST['Person_name'];
$Expediente=$_POST['Expediente'];
$Sexo=$_POST['Sexo'];
$Edad=$_POST['Edad'];
$Domicilio=$_POST['Domicilio'];
$numero=$_POST['Numero'];
$colonia=$_POST['Colonia'];
$Ciudad=$_POST['Ciudad'];
$Parentesco=$_POST['Parentesco'];
$ClinicaAds=$_POST['ClinicaAds'];
$Dependencia=$_POST['Dependencia'];
$Entidad=$_POST['Entidad'];
$Foraneo=isset($_POST['Foraneo']) ? 1 : 0;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "issste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario, Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero', '$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo', '$Parentesco' FROM paciente
WHERE NOT EXIST(
SELECT RFC, Diagonal FROM paciente WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20') LIMIT 1 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
when i run my program i get this error
"you have an error in your sql syntax check the manual that corresponds to your mysql server version"
Modified your query, try something like this:
INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario,
Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero',
'$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo',
'$Parentesco'
WHERE NOT EXISTS( SELECT RFC, Diagonal FROM paciente
WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20' LIMIT 1 )

Update values in a row if there is a same name in a column (with PHP in MySQL)

I have a database with three columns: ID, userName, feedback
I want the feedback value to be updated when the userName is same.
my php code:
<?php
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['name'];
$value2 = $_POST['message'];
$sql = "INSERT INTO js (userName, feedback) VALUES('$value', '$value2');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
};
$conn->close();
?>
If you want to do it with mysql you first of should define a unique index on the userNamecolumn.
ALTER TABLE js
ADD CONSTRAINT u_userName UNIQUE (userName)
The edit your insert query like this:
INSERT INTO js (userName, feedback) VALUES ('$value', '$value2')
ON DUPLICATE KEY UPDATE feedback=VALUES(feedback);
Now if the duplicate key violation is hit by mysql, the value for feedback will be updated while inside the row where your username equals.
Or you implement a update logic inside php and detect if there already is an entry inside the table with the same username.

im getting error when performing insert multiple records

<?php
session_start();
if(isset($_SESSION['id']))
$servername = "localhost";
$dbname = "school";
// Create connection
$conn = mysqli_connect($servername, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$teacher_id=$_SESSION['id'];
$student_id=$_POST['student_id'];
$subject=$_POST['subject'];
$description=$_POST['description'];
$sql="INSERT INTO t_sent (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";
$sql .="INSERT INTO p_inbox (teacher_id, student_id, subject, description)
VALUES
('$_SESSION[id]', '$_POST[student_id]', '$_POST[subject]', '$_POST[description]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
and im getting this error message when im adding records
Error:
INSERT INTO t_sent (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')INSERT INTO p_inbox (teacher_id, student_id, subject, description) VALUES ('Badri', 'ca11099', 'cm ', 'cm')
No database selected
I don't know what I'm missing
I think you missed out the syntax for mysqli_connet
mysqli_connect(host, user,password, db);
Please let me know if it didnt work for you.
First of all it looks like you are incorrectly using an if statement - namely
if(isset($_SESSION['id'])).
That if statement will only apply to the very next line ($servername = "localhost";). You need to wrap the code you want that statement to apply to with { } (judging by your code, it's every line after that).
Your parameters for mysqli_connect() are wrong - it should be
mysqli_connect($servername, $username, $password, $dbname);
You are missing the username and password which should go before the database name.
You're also not sanitizing or escaping your input which is very bad and can lead to SQL injection attacks. You should never directly take user input and run queries against that.
Use correct mysqli_connect() with all the parameters:
<?php
$con = mysqli_connect($servername, $username,$password, $database_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Also, You can select database using mysqli_select_db() function

Categories