make column as same from id - php

I need your help, I have a table whith two column, an id and numpos, i want that the id and numops has the same result.
exemple :
$cnx = mysql_connect( "localhost", "root", "" );
$db = mysql_select_db( "maincourante" );
$sql = mysql_query("INSERT INTO ops (id) values('')");
$req = mysql_query("SELECT LAST_INSERT_ID() as id FROM ops");
$data = mysql_fetch_array($req);
$upd = mysql_query("UPDATE `ops` SET `numops`=`idops` WHERE `idops`=$data");
mysql_query($upd, $cnx) or die(mysql_error());
mysql_close();`
thanks for your help

Try this:
This works for mysql:
INSERT INTO ops (`numops`) VALUES ((SELECT LAST_INSERT_ID())+1);
This works for php:
mysql_query("INSERT INTO ops (`numops`) VALUES (0)");
mysql_query("UPDATE ops `numops` ='".mysql_insert_id()."' WHERE `id` = '".mysql_insert_id()."'");
Or
mysql_query("INSERT INTO ops (`numops`) VALUES ('".mysql_insert_id()."')");
// this will only works if there is the same query executed before this.

Related

How to insert or update foreign key values using PHP

I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>

Why are these UPDATE & INSERT INTO queries not working? PHP & MySQL

I have 2 queries. Query #1 updates some things in the database, and Query #2 inserts some data into the table.
Code:
function add_like($id) {
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("UPDATE `posts` SET `post_likes` = `post_likes` + 1 WHERE `id` = '$id'");
$likes_query = $connection->query("INSERT INTO `likes` VALUES (".$_SESSION['user_login'].", $id)");
}
The first query ($query) should add 1 like to the database. So starting at 0 it should +1. Instead, it does +12.
The second query ($likes_query) does not INSERT INTO likes.
Any help would be much appreciated. Thanks!
UPDATE:
Changed the second query to:
$likes_query = $connection->query("INSERT INTO `likes` (`user_id`, `post_id`) VALUES ('$user', '$id')");
Final code:
function add_like($id) {
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$user = "";
}
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("UPDATE `posts` SET `post_likes` = `post_likes` + 1 WHERE `id` = '$id'");
$likes_query = $connection->query("INSERT INTO `likes` (`user_id`, `post_id`) VALUES ('$user', '$id')");
}
All issues fixed. Thanks for all your comments!

Mysql INSERT ... ON DUPLICATE KEY UPDATE responce

Hello I have a table A and I want when a new value (not UPDATE) is inserted in that table to do an INSERT in table B, I tried to play with the responce of the $query INSERT INTO .. ON DUPLICATE KEY UPDATE but no luck, it always returns 1.
$query = "INSERT INTO table ".$fields." VALUES ".$values." ON DUPLICATE KEY UPDATE updated=1"
$response = $dbc->query($query);
if($response == 1)
I have also tried a 'hack' lets say, putting the UPDATE above the INSERT so if the entry doesnt exist to fail but that again returns 1 everytime.
$query = "UPDATE table SET updated=1 ..;
$response = $dbc->query($query);
if($response == 1)
This should work:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "INSERT INTO tableA ".$fields." VALUES ".$values." ON DUPLICATE KEY UPDATE updated=1");
if(mysqli_affected_rows($link)==1)
{
mysqli_query($link, "INSERT INTO tableB ".$fields." VALUES ".$values.");
}
?>
Thanks #boomoto for helping me figuring out the answer:
$query = "UPDATE tableA ..
$response = $dbc->query($query);
if(mysqli_affected_rows($dbc)==0){
$query2 = "INSERT INTO tableB ..
$response2 = $dbc->query($query2);
$query = "INSERT INTO tableA ..
$response = $dbc->query($query);
}
}

Updating data in MySQL database

I am having problem updating an existing row in my database. What I need to do is add a record to a field named "Time_Out". This field is on the same row as with the "Time_In", "username", and "date_added". The Time_In is working perfectly fine. This is the code I've used:
date_default_timezone_set('Asia/Taipei');
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added')");
if(!$con) {
die('Could not connect to the database' . mysql_error());
mysql_close($con);
}
else
header("Location: etc.php");
For the Time_Out, I have removed the "INSERT INTO ..." line and changed it into:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");
but the record in the Time_Out field in my database is still showing 0:00.
By the way, my date_added is set to Date and the Time_In and Time_Out is set to Time.
I would really appreciate it if someone could show me how to do this using PHP. Thank you in advance.
You're missing single quotes around your non-numeric data. Try:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");
Your code has a few issues. First in this chunk you are using mysqli_* and mysql_* extensions mixed together when they should all be mysqli_*:
date_default_timezone_set('Asia/Taipei');
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added');");
if (!$con) {
die('Could not connect to the database' . mysqli_error($con));
mysqli_close($con);
}
else
header("Location: etc.php");
Specifically it was in your if (!$con) { check. Look at the cleaned up example now. But also, your update does not have single quotes around string values:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");
So it should be like this:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");
But to make your life easier, you might want to reformat your queries like this:
$query = "UPDATE time_logs SET Time_Out = '" . $time_added . "' WHERE username = '" . $user . "';";
$save = mysqli_query($con, $query);
Note how I set the query in a separate string & then added concatenation to the string itself for the variables. This makes it easier to spot issues like this in text editors in my humble option. I also ended each of your queries with a semicolon (;) since that again makes it clearer to me that is the true end of the query statement.

Adding multiple fields to DB using PHP

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);
}

Categories