I need to insert the details (name, id , number )of many documents into database if they are not already existing and if they exist i just need to do a update for any changed information. I have arrived at the following code but it doesn't work. I am new to this and need help on this.
foreach($A->Documents -> Document as $Document)
{
$query = "SELECT * from table where id = '".$Document->id."'";
$outcome = mysql_query($query) or die(mysql_error());
if(($outcome)&&(mysql_num_rows($result)>0)){
echo "Document already available" ;
while($row = mysql_fetch_object($outcome)){
if(!($outcome->name == $document->name)){
$update= "UPDATE table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
else
{
$insert= "INSERT table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
}
}
}
Use $row->name instead of $outcome->name. and your INSERT statement is wrong.
while($row = mysql_fetch_object($outcome)){
if(!($row->name == $document->name)){
$update = "UPDATE table SET name ='".$Document->Name."' WHERE id = ".$Document->id;
mysql_query($update) or die(mysql_error());
}
else {
$insert = "INSERT INTO table (name) VALUES('".$Document->Name."')";
mysql_query($insert) or die(mysql_error()); // $insert not $update
}
}
Note: Stop using mysql_* functions! Use PDO or mysqli_* instead. And use prepared statements
Change the
mysql_query($update) or die(mysql_error());
To:
$insert = INSERT into table_name values(" values");
mysql_query($insert) or die(mysql_error());
in the else condition
Issue is with $result variable with in if statement
( if(($outcome)&&(mysql_num_rows($result)>0)){)
It should be $outcome because you initialized query output to $outcome variable
First of, dont yse mysql_ functions. Read the docs (read the warning).
use mysqli or PDO instead.
Then, your INSERT statement is wrong.
INSERT INTO table (col1) VALUES (value_for_col1);
Related
I need to insert values into multiple table. Please correct my code because it just double the inserted value on table_attendace
if(isset($_POST['text']))
{
$text =$_POST['text'];
// insert query
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW())";
$query =mysqli_query($conn,$sql) or die(mysqli_error($conn));
if($query==1)
{
$ins="INSERT INTO table_attendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn));
if ($quey==1) {
$_SESSION['success'] = 'Action Done';
}else{
$_SESSION['error'] = $conn->error;
}
}
}
In the second query, you reused the first query $sql again, instead of using $ins.
It should be
$quey=mysqli_query($conn,$ins) or die(mysqli_error($conn));
you can write two queries in single variable with semicolon then you can save the same data in both table.
And
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn)); -> in this line you placed the $ins variable wrongly instead of $ins.
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW()); INSERT INTO table_ttendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I am currently using the following function:
if(isset($_REQUEST["function"]) && ($_REQUEST["function"] == "setnm")){
$value = $_REQUEST["value"]; //field to edit
$con=mysqli_connect("localhost", "root", "", "hike_buddy");
//Check Connection
if(mysqli_connect_errno())
{
echo "failed to connect:".mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO user_com (name) VALUES ('$value')");
mysqli_close($con);
}
How can I alter this code so it will change the value of two fields?
For instance I have a comment and a name column and I want to update them both (different values) with one function.
Never use un-escaped strings specified by the user in your database queries.
So, if you're using mysqli:
$value1 = $con->real_escape_string($_REQUEST['value_1']);
$value2 = $con->real_escape_string($_REQUEST['value_2']);
$query = "INSERT INTO my_table (column_1, column_2) VALUES ('$value1', '$value2')";
$con->query($query);
Are you trying to INSERT new data in the database or UPDATE existing data?
If you want to update data, you should use the UPDATE statement:
$query = "UPDATE my_table SET column_1 = '$value1', column_2 = '$value2' WHERE my_table_key = '$key'";
Also, you need to escape these variables like har-wradim suggested.
You can do the following:
if(isset($_REQUEST["function"]) && ($_REQUEST["function"] == "setnm")){
$value = $_REQUEST["value"]; //field to edit
$comment = $_REQUEST["comment"]; //This is your comment
$con=mysqli_connect("localhost", "root", "", "hike_buddy");
//Check Connection
if(mysqli_connect_errno())
{
echo "failed to connect:".mysqli_connect_error();
}
//Edit the query like so to update insert the comment along with the name.
mysqli_query($con, "INSERT INTO user_com (name, comment) VALUES ('$value', '$comment')");
mysqli_close($con);
}
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL); SELECT LAST_INSERT_ID()";
$result8 = mysql_query($sql_comp5);
$flag_control=0;
while ($row = mysql_fetch_assoc($result8, MYSQL_BOTH))
{
$flag_control=$flag_control+1;
$id_t[$flag_control]=$row['LAST_INSERT_ID()'];
}
for ($buc = 1; $buc <=$flag_control; $buc++)
{
$id_tiquet=$id_t[$buc];
}
I am doing the correct? Or i'm wrong?
Very thanks!!
You can't do two queries use mysql_* functions. You need mysqli::multi_query() for that. To get the last insert ID using mysql_* use mysql_insert_id():
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL);";
$result8 = mysql_query($sql_comp5);
$id = mysql_insert_id($result8);
Remove the second query - and use php's mysql_insert_id()
$sql_comp5 ="INSERT INTO tiquets (Id_Tiquet) VALUES (NULL)";
$result8 = mysql_query($sql_comp5);
$insertedId = mysql_insert_id();
Some code starts with selecting data then check if row numbers are 0 to insert then continue the normal process. The problem is that the normal process is depending on the select statement which does not exist because it was stored before the insert. How can I refresh data request inside PHP without ajax or anything related to html? Here's an example to explain:
$user = $_GET['user']; // not stored user
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
$rownum = mysql_num_rows($select);
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
/* Here comes the problem */
if($row['something'] == 0){
die("Not found !"); // THIS if returns true since it was not found at first place before inserting
// i want it to refresh the $select data so it could be read as 1
}
How I solved it so far is by repeatedly using the $select and $row code below the insert statement
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
[..]
I want a simpler way to do this
If you know whats in the newly created record, you could just create a new array $row=array('username'->'bob', ...);
BUT if you have default values in the table, or add other things later, you going to have to do a second select.
$user=urldecode($_GET['user']);
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($select);
}
else
{
mysql_query("INSERT INTO table (username, something) VALUES ('".mysql_real_escape_string($user)."', 1)");
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)==0) die("MAJOR ERRORS IN SQL");
$row = mysql_fetch_array($result);
}
I prefer to use $result as this is the result of you running the query.