When I use this code, I get one record for each id stored in the users table. Instead, I want to be able to insert only 1 record each time, the one that matches the logged users id.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
You must have a where clause in your select statement
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users WHERE usernamecolumn= currentusername ;
Related
Here is my code-
<?php
session_start();
$con = mysqli_connect("localhost", "root", "", "placement")
or die("Failed to connect MySQL: " . mysqli_error()); // Connecting to MySQL Database
// Variable Declaration
$StateName = mysqli_real_escape_string($con, $_POST["txtStateName"]);
$Description = mysqli_real_escape_string($con, $_POST["txtDescription"]);
$CountryName = mysqli_real_escape_string($con, $_POST["selectCountryName"]);
$CountryId = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";
// Insert Query
$sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId) VALUES ('$StateName', '$Description', '$CountryId')";
if(!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
header("Location: frmAddState.php?msg=1");
}
mysqli_close($con);?>
CountryId in tbl_state_master is a foreign key and it is referenced to primary key of tbl_country_master. I'm not able to insert data as I'm getting error.
You never executed the query that's supposed to return the country ID. You just set $CountryId to the SQL string. It should be:
$sql = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
$CountryId = $row['CountryId'];
}
But ou don't need two separate queries, do it in just one:
$sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId)
SELECT '$StateName', '$Description', CountryId
FROM tbl_country_master WHERE CountryName='$CountryName'";
I have a problem with my code. I have a table called "users" with an "id" field.I want to copy the id value to another table called "aircondition" . This is the code that inserts values into the aircondition table .The problem is that when I use this code I get 0 in the new id field instead of the user.id
<?php
$con=mysqli_connect("localhost","george","george123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
VALUES ('SELECT id
FROM users', '$acname', '$btu', '$space', '$energyclass')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
Use this query
INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users
<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
// echo $row['Name']. " - ". $row['email'];
// echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>
i have the above code i am trying to insert data from one table to another
The above code do not returning any error but it do not puts any data to second table "other_user"
There is an error in INSERT query - you have to enclose strings in quotes, like this:
"INSERT INTO other_user (user_id, username, email)
VALUES ($userid, '$username', '$email')"
A single query would be enough:
$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
SELECT id, Name, email FROM users WHERE status='ACTIVE'");
No need for an agonizing slow row by row insert.
PS: The original error was leaving out quotes around your values.
You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection
I think you should carefully check the table design of your new table.
Check if the column names and types are what you expect.
Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.
I want to modify my code so instead of just inserting a new row in the MySQL table, it can check to see if there is one with the same item number, and update it.
php code
<?php
$con=mysqli_connect("localhost","root","root","inventory");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You can use ON DUPLICATE KEY UPDATE syntax,
$sql = "
INSERT INTO `current stock` (ItemNumber, Stock)
VALUES ('$_POST[ItemNumber]', '$_POST[Stock]' )
ON DUPLICATE KEY UPDATE
Stock = '$_POST[Stock]'
";
ItemNumber should be primary/unique key in this case
I need the id of the last inserted object. I use prepared statements to avoid sql injection.
But i'm not sure how to obtain the id.
$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name,
middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";
if (!($stmt = $mysqli->prepare($sql)))
echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param('sissssss',
$faculty['id'],
$faculty['term'],
$faculty['role'],
$faculty->name->prefix,
$faculty->name->first,
$faculty->name->middle,
$faculty->name->last,
$faculty->name->suffix
);
if (!$stmt->execute())
echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
$result = $stmt->insert_id;
echo "\n Result:" . $result;
$stmt->close();
The result is 0 always despite there being an entry in the database
Solution
The element was being inserted into the database. The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked.
Try changing $result = $stmt->get_result(); to $result = $stmt->insert_id;
get_result() is more for SELECT queries, rather than INSERTs.
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-stmt.insert-id.php