Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have two submit buttons that get values from two forms and insert them in a database. The problem is that I need to get the last inserted id from the first table (courses) to insert into the second table (students) but it does not work. This what I did:
<?php
$course_name = // the value of the field for the course name
$student_name = // The first name of the student
$student_age = // The age of the student
$last_id = // The last id of table courses
if(isset($_POST['submit1'])){
$query1 = "INSERT INTO courses (course_name)VALUES ('$course_name')";
if ($object->query($query1) === true){
$last_id = LAST_INSERT_ID();
$good = "the course has been created";
}
else{
$bad = "Error: " .$query1.$object->error;
}
}
if(isset($_POST['submit2'])){
$query2 = "INSERT INTO students (course_id,student_name, student_age)VALUES ('last_id','$student_name','student_age')";
if ($object->query($query2) === true){
$good = "the student has been created";
}
else{
$bad = "Error: " .$query2.$object->error;
}
}
?>
I do not know why it does not work.
You have not mentioned if you are using PDO or mysqli etc etc. If it's mysqli it $mysqli->insert_id;
if ($object->query($query1) === true){
$last_id = $object->insert_id
$good = "the course has been created";
}
OTH, if you are using PDO it's lastInsertId
if ($object->query($query1) === true){
$last_id = $object->lastInsertId()
$good = "the course has been created";
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can anyone tell where am I wrong in the query. The database in not updating irrespective of the value
<?php
// ================= UPDATE =========================
if ($_POST['SUBMIT']=='SUBMIT')
{
$fixture_id = "$_GET[id]";
$m_date = "$_POST[match_date]";
$m_time = "$_POST[match_time]";
$m_report = "$_POST[match_report]";
$m_a_result = "$_POST[team_a_result]";
$m_b_result = "$_POST[team_b_result]";
$updt = mysql_query("UPDATE `fixture` SET match_date='$m_date', match_time='$m_time', match_report='$m_report', match_a_result='$m_a_result', match_b_result='$m_b_result', status = 1 WHERE id = '$fixture_id'");
header("location:view_fixture.php?msg= You have inserted result successfully...");
}
else
{
header("location:result_update.php?msg= Something went wrong...");
}
// ================================================================================
?>
Before executing this make sure your submit button have a string value of "SUBMIT"
Try this ..
<?php
$fixture_id = $_GET[id];
if ($_POST['SUBMIT']=='SUBMIT')
{
$m_date = $_POST['match_date'];
$m_time = $_POST['match_time'];
$m_report = $_POST['match_report'];
$m_a_result = $_POST['team_a_result'];
$m_b_result = $_POST['team_b_result'];
$updt = mysql_query("UPDATE `fixture` SET match_date= '$m_date', match_time='$m_time', match_report='$m_report', match_a_result='$m_a_result', match_b_result='$m_b_result', status = 1 WHERE id = '$fixture_id'");
header("location:view_fixture.php?msg= You have inserted result successfully...");
}
else
{
header("location:result_update.php?msg= Something went wrong...");
}
?>
Please DO NOT USE mysql_* . It is now deprecated
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm beginner in PHP MySQL, I would like to ask if this possible:
I have ADD NEW EMPLOYEE page after I submit, I want to have simple summary information of the added employee like
Something like opening a new window page:
Agent Code: The Agent code of the employee newly added
Name: Name of the Employee
Type: Type of the employee
Here is PHP Code in my ADD NEW EMPLOYEE page:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_POST['btn-signup']))
{
$agentCode = mysql_real_escape_string($_POST['agentCode']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$aFName = mysql_real_escape_string($_POST['aFName']);
$aLName = mysql_real_escape_string($_POST['aLName']);
$aMName = mysql_real_escape_string($_POST['aMName']);
$aSuffixName = mysql_real_escape_string($_POST['aSuffixName']);
$aContact = mysql_real_escape_string($_POST['aContact']);
$aAddress = mysql_real_escape_string($_POST['aAddress']);
$aGender = mysql_real_escape_string($_POST['aGender']);
$utype = mysql_real_escape_string($_POST['utype']);
$loctype = mysql_real_escape_string($_POST['loctype']);
$ipadd = mysql_real_escape_string($_POST['ipadd']);
if(mysql_query("INSERT INTO accounts(agentCode, password, agentFname, agentMname, agentLname, aSuffixName, agentContact, agentAddress, agentGender, user_type, location_type, ip_add)
VALUES('$agentCode', '$pass', '$aFName', '$aMName', '$aLName', '$aSuffixName', '$aContact', '$aAddress', '$aGender', '$utype', '$loctype', '$ipadd' )"))
{
?>
<script>alert('Successfully added!');</script>
<?php
} else {
?>
<script>alert('Agent Code is not available!');</script>
<?php
}
}
?>
You can do it in 2 ways.
1) You will have all posted for db from the form which you used to insert the values to you database. You can use same values to display there.
2) Capture the last insert id, on successfully inserted the data, fetch the data based on that id and display in view.
mysql_* to mysqli_*
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qry = "INSERT INTO accounts(agentCode, password, agentFname, agentMname, agentLname, aSuffixName, agentContact, agentAddress, agentGender, user_type, location_type, ip_add)
VALUES('$agentCode', '$pass', '$aFName', '$aMName', '$aLName', '$aSuffixName', '$aContact', '$aAddress', '$aGender', '$utype', '$loctype', '$ipadd' )";
mysqli_query($con, $qry);
// Print auto-generated id
$last_inserted_id = mysqli_insert_id($con);
echo "Last Inserted ID: " . $last_inserted_id;
// Now you can perform a select query by using this ID and show
// Agent Code: The Agent code of the employee newly added
// Name: Name of the Employee
// Type: Type of the employee
mysqli_close($con);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am a beginner . I made a php html combined page(viewemployees.php) to display my table from oracle data base. It worked fine. Then i made a page to edit my data base table(editemployees.php). that page has two functions. It displays the original table and a simple form which should contain the elements to update the table. When we place values in the form it directs us to a new php page(een.php) where it updates table and returns back to editemployees.php showing the updated table. but i am stuck when i fill in the form AND NOTHING happens. Even I have placed a condition that to echo a line if new value field is null. still that line is not echoed. This is some weird thing. I am posting both of my edit and view pages code click the link. kindly help.
In simple my table update is not working and showing undefined variable error at line 4 of een.php. Why is taht variabl undefined?? can anyone help please
https://www.dropbox.com/sh/xtuvotdy7c9wr1v/AADrNSlC_EJ0YkyDDkhe8mKGa?dl=0
<?php
include("connection.php");
$empid = $_POST['EMPLOYEE ID'];
$field = $_POST['EDIT FIELD'];
$nfield = $_POST['NEW VALUE'];
echo $field;
if( empty($_POST['NEW VALUE'] )){
echo "type new field properly";
}
else
{
$e = filter_var($empid, FILTER_SANITIZE_EMAIL);
$f = filter_var($field, FILTER_SANITIZE_EMAIL);
$nf = filter_var($nfield, FILTER_SANITIZE_EMAIL);
}
if( $e==$empid && $f==$field && $nf==$nfield)
{
if ($field=="age" || $field=="sal"){
$sel = "seleect * from employ";
$st = oci_parse(conn, $sel);
oci_execute($st);
$query = " update employ set $field = $nfield where empid = $empid";
$stmt = oci_parse($conn,$query);
oci_execute($stmt, OCI_COMMIT_ON_SUCCESS);
oci_free_statement($updateTitleInserted);
oci_close($conn);
echo oci_error();
header("Location: home.html");
}
else{
$query = "update employ set $field = '$nfield' where empid = $empid";
$stmt = oci_parse($conn,$query);
oci_execute($stmt,OCI_COMMIT_ON_SUCCESS);
oci_free_statement($updateTitleInserted);
oci_close($conn);
echo oci_error();
echo $field;
}
}
else
echo "wrong data entry go back and enter again";
?>
This line does not make sense.
$empid = $_POST["EMPLOYER ID"];
A post variable name cannot contain a space.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to write a script that does the following. Takes a users email and added's it to a database however if the users email already exists it rejects.
<?
require_once('includes/db.php');
$email = mysqli_real_escape_string($link, $_POST['email']);
$dupesql = "SELECT * FROM emails where (email = '$email')";
$duperaw = mysqli_query($link, $dupesql);
if(int mysql_num_rows($duperaw) > 0){
echo 'Error already in there';
}
else {
$sql = "INSERT INTO emails(email)
VALUES('$email')";
$result = mysqli_query($link, $sql);
header('Location: poll/poll.php');
}
// close mysql
mysqli_close($link);
?>
Why not let mysql take care of it? When you already want email to be unique, then define an unique index for email :
CREATE UNIQUE INDEX email_index ON emails (email)
now you only have to check if any rows has been affected after insert :
if (mysqli_affected_rows()>0) {
//success, email inserted
} else {
// rejected
}
By that you'll spare a call to the database and make the code more simplistic, imho.
try this
$mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
Change your code as follow:
$dupesql = "SELECT * FROM emails where email = '$email'";
$duperaw = mysqli_query($link, $dupesql);
if(mysql_num_rows($duperaw)==1){
echo 'Error already in there';
}
You are mixing mysqli_ with mysql_ which is the main problem here.
Use mysqli_num_rows instead of mysql_num_rows
You should not mix mysqli() and mysql().
And remove int error casting.
//...
if(mysqli_num_rows($duperaw) > 0){
echo 'Error already in there';
}
//...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Why isn't this code working?
$welcome = mysql_query("SELECT welcome FROM users WHERE id = '" . $_SESSION['user']['id'] . "'");
if($welcome == '0')
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
$_SESSION['user']['id'] returns as 1, by the way.
MySQL returns a resource on success, false on error, not a value from the query. Try this:
$welcome = mysql_query("SELECT welcome FROM users WHERE id = '" . $_SESSION['user']['id'] . "'");
$row = mysql_fetch_assoc($welcome);
if($row['welcome']== '0')
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
You shouldn't build your query like that as you'll not be protected from a SQL Injection Attack.
$query = sprintf("SELECT welcome FROM users WHERE id = %d", $_SESSION['user']['id']);
// Perform Query
$result = mysql_query($query);
Once that has finished you then need to fetch from the result, you cannot just query it.
if(!$result)
echo "Error"; // Deal with it
$row = mysql_fetch_assoc($result);
echo $row['welcome'];
mysql_free_result($result);
According to MySQL documentation, the resource is returned if the select statement is successful, or 'false' if the statement fails.
Although there's a better, more secure way to achieve what you are trying to accomplish, your statement can be revised simply to :
if($welcome === false)
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
That will work, but as I said earlier, the whole code needs to be updated to a more secure version.