Sending message back if table row has value - php

For example, have a query like this:
<?php
$sql = "INSERT INTO oppgave
(username, besvarelse, modulid)
VALUES
('$username', '$besvarelse', '$modulid');
";
mysql_query($sql, $tilkobling);
?>
How can I do this:
If modulid row is not empty, echo "you have sent this modul before";

Try this:
<?php
$sql = "INSERT INTO oppgave(username, besvarelse, modulid)
select '$username', '$besvarelse', '$modulid'
from dual
where not exists (select modulid from oppgave where modulid='$modulid')";
$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
echo "Failed to insert duplicate modulid";
}else{
echo "inserted";
}
?>
In this SQL Query, it will allow insert only if $modulid isn't already exist in database table. Such situation you can also handle by applying UNIQUE constraint to table column (but remember, it allows NULL value at once)

Best way to do this, is by not allowing duplicates.You can do this with your SQL QUERY.Build your query by this:
$sqlString ="INSERT INTO oppgave('" . $username . "', '" . $besvarelse . "', '" . $modulid . "')
SELECT username, besvarelse, modulid
FROM oppgave
WHERE NOT EXISTS (SELECT *
FROM oppgave
WHERE modulid IS NULL)";
Please check all names and tablenames first ;)
Hope this helps.If this the answer, please mark as answer.

Related

how do I check if a username is unique (php, MySQL) [duplicate]

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

PHP inserting data from one table to another

<?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.

How to get the primary key which is an auto-increment for the row just entered in PHP?

I have a SQL query like
$result = mssql_query("INSERT into CALLER
( status, media, media_2, first_name, last_name, street_address, city,
state, zipcode, home_phone_no, mobile_phone_no,email, problem,
medical_condition, comments, updated_date )
VALUES
('CALL', '$media', '$media_2','$fname','$lname', '$street_addr', '$city',
$state','$zip', '$phone_alt', '$phone','$email','$problem','$mc',
'$comments',GetDate() ); ");
The primary key for the table CALLER is an auto-increment. How can I get the Primary Key of the row just inserted after this query ?
Correction: use this.
$query = mssql_query("SELECT ##IDENTITY");
$row = mssql_fetch_assoc($query);
Well if you have any CANDIDATE KEY in the table, you can use that to retrieve the last inserted row.
Say you have a candidate key consisting of columns status, email and problem.
Then you can execute a query like this just after your insert.
$query = "SELECT id FROM CALLER
WHERE
status = '" . $status . "'
AND email = '" . $email . "' AND
problem = '" . $problem . "'";
mssql_query($query);
This will return the id for that entry.
Update
I just saw this in a comment by Mikael to Femi's Answer, you can use SCOPE_IDENTITY()
It returns the las insert id for the current connection in current scope. So it should work for you even if multiple instances do inserts which are interleaved.
So you can simply do this after the insert
$res = mssql_query('SELECT SCOPE_IDENTITY()');

Check if value exists before inserting into MySQL DB in a PHP script

I've looked for similar questions with no success.
I have this piece of code:
form1.php
$query = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')";
$result = mysql_query($query) or die ("Query Failed: " . mysql_error());
And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?
Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

Odd Mysql issue on insert

Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.

Categories