What do you put in the parentheses of mysql_insert_id()? - php

I tried setting a variable like this: $test_id = mysql_insert_id($dbc); because I wanted to get the id of the last row inserted. I am able to connect to the database and insert the row but the next line (setting $test_id) it says this: supplied argument is not a valid MySQL-Link resource . Any ideas?
Here's the code:
$user_id = $_SESSION['user_id'];
$q = "INSERT INTO tests (user_id, title, subject, creation_date) VALUES ('$user_id', '$title', '$subj', NOW())"; //query to insert test details into tests table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$test_id = mysql_insert_id($dbc);
if (mysqli_affected_rows($dbc) == 1) {//if the query ran correctly and the test details were added to the database
$q = "INSERT INTO content (test_id, field1) VALUES ($test_id, '$content')"; //query to insert test content into content table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$dbc is defined like this:
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASS, DB_NAME);

From the comments:
Oh, I see now. You're mixing mysql_* with mysqli_* functions. Those are different libraries. They don't mix. Use mysqli_insert_id() instead.

You should put the link identifier (the output of mysql_connect(), not mysql_query())
mysql_insert_id implicitly calls SELECT LAST_INSERT_ID() which is session-specific.

Normally you can leave out that parameter; it will know that you have a database connection open. If you want to specify the connection, use the return value from mysql_connect:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// later
echo mysql_insert_id($dbc);
Again, this is normally not necessary.
Also keep in mind that mysql_insert_id will only work after you've made an INSERT query where an index column with AUTO_INCREMENT was incremented. It will not return the latest ID that was inserted at some other time before the current session. For that you you could for example do:
SELECT MAX(id) FROM some_table;

The problem is that you're using a MySQLi resource in a MySQL function (note the missing i). There are 2 different extensions there. If you're using mysqli, don't switch to mysql. So just change that function to mysqli_insert_id($dbc);

Related

php add to database with insert statment

I have a simple insert statement that should use $GLOBALS that has my connection string in. Problem is that it does not insert the data. Have I done this correctly?
Insert.php
<?php
require 'core/init.php';
$Name = $_REQUEST["Name"];
$Venue = $_REQUEST["Venue"];
$Category = $_REQUEST["Category"];
$query = "INSERT INTO bands (Name, Venue, Category)
VALUES ('$Name', '$Venue', '$Category')";
mysql_query ($query,$GLOBALS)
or die ("could not add to database");
echo("You have added: <br />");
$result = mysql_query("SELECT * FROM bands ORDER BY Band_id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
echo $row['Name']. "" . $row['Venue']. "" . $row['Category'];
echo "<br />";
}
?>
You need to connect mysql with mysql_connect() function then select database with mysql_select_db() function then you can call mysql_query function
you just cant execute queries with query string parameter you need to execute that connection query first and then select your database
And i suggest you to use mysqli instead of mysql cuz mysql methods will be deprecated soon
You don't put whole $GLOBALS variable in your mysql_query() call. You put the specific variable with the connection string only:
mysql_query($query, $GLOBALS['connection']) // Assuming you called the connection var "connection"
or die ("could not add to database");

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

Why does mysql_insert_id() return 0?

When I run this code
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)... ";
$mysqlid = mysql_insert_id($sql_select->db);
echo ($mysqlid);
I get the error message
mysql_insert_id(): supplied argument is not a valid MySQL-Link
I have tried this variation;
$mysqlid = mysql_insert_id();
echo ($mysqlid);
but that returns a 0 which, according to the documentation, means an auto_increment field was not found. The only thing I can think of is that I am not calling the auto_increment column in the $sql_select, but there is an auto_increment column in there; will that affect the behavior of mysql_insert_id?
you need to actually run the query first:
$sql= "INSERT INTO `database`.`table`(Columns) VALUES (Values)...";
$result = mysql_query($sql);
and then after that:
$id = mysql_insert_id();
echo $id
Let me know if you have still problems.
That is because $sql_select->db is not a valid MySQL Link
What you are looking for is something like this:
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)...
$result = mysql_query($sql_select);
$mysqlid = mysql_insert_id($result->db);
$result is a valid MySQL resource.
Also don't forget to have created a mysql connection
NOTE: While I used code for the original MySQL driver it's use is discouraged. Instead you want to use MySQLi or PDO_MySQL
You need to run your query:
if($result = mysql_query($sql_select)){
$mysqlid = mysql_insert_id();
echo $mysqlid;
}
Cheers
your connection of mysqli is an object...so try this....
$mysqli = new mysqli("localhost", "user", "password", "dbname");
after inserting try this..
echo $mysqli->insert_id;

Cant insert data into second database connection

See the code below, there are two databases connections.
First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list'
When I tried SQL query manually in phpMyAdmin and it work fine...
$db_new = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("menu_new", $db_new)) {
die("Cant connect menu_new DATABASE");
}
$db_old = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("old_menu", $db_old)) {
die("Cant connect old_menu DATABASE");
}
$SQL_old = "SELECT * FROM old_table";
$q = mysql_query($SQL_old, $db_old);
while ($row = mysql_fetch_assoc($q)) {
$name = $row['name'];
$SQL = "INSERT INTO tbl_name (fullname) values ('$name')";
//Problem Here - It wont insert into second database
mysql_query($SQL, $db_new) or die(mysql_error($db_new));
}
Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion.
It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server.
Thanks #Konerak for suggestion and that does work!
To Insert/Select data from Database connection, you will have to include database name before the table name.
For Example
From:
mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
To:
mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
That is really odd though.

PHP mysql_query parameter order

I'm a bit of a noob but I am having trouble finding the answer to this question. I have two pieces of code and both work but I'm not sure why.
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Retrieve the score data from MySQL
$query = "SELECT * FROM table";
$result = mysqli_query($dbc,$query);
mysqli_close($dbc); // close db
In the instance above the connection is the first mysql_query parameter and then the sql query. This came from a book and isn't how the PHP manual defines it as far as I can see.
In the next example the sql is entered first, then the connection and I have to specifically use mysql_select_db. Why do they both work?
//db connection
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$db_selected = mysql_select_db("database",$dbc); // select the db
$sql = "SELECT * from table"; // sql query
$result = mysql_query($sql, $dbc); // make query on db
mysql_close($dbc); //close the connection after data is acquired
Thanks in advance for any illumination you can supply.
Your first example
$result = mysqli_query($dbc,$query);
Is a function call to the newer mysqli library, http://www.php.net/manual/en/mysqli.query.php
Your second example
$result = mysql_query($sql, $dbc); // make query on db
Is a function call to the mysql library, http://www.php.net/manual/en/function.mysql-query.php
Both calls match the signature and order of arguments to those functions.
$result = mysqli_query($dbc,$query); // MySQLi (link, query)
$result = mysql_query($sql, $dbc); // MySQL (query, link)
You're using mysqli_query in the first example, and mysql_query in the second.
Two different function with two different parameter order, that's why I "love" PHP.
Because mysql_query() expects query as first parameter and mysqli_query() expects your query as 2nd.
mysqli_query
mysqli_query ( mysqli $link , string $query [, int $resultmode ] )
mysql_query
mysql_query ( string $query [, resource $link_identifier ] )
mysql_select_db() is required because mysql_connect() doesn't have database as parameter, instead of mysqli_connect().
The function mysql_select_db let you choose another db along your code without the need of 'another' new connection, using the same connection you started with mysql_connect.

Categories