mysql_insert_id not working - php

Apologies for the vague title, here's my problem:
The goal of my code is to insert a new row into a table that has an auto-increment field. After the insert, I want to get the value of the auto-increment field that has just been generated.
Here's my table defintion:
CREATE TABLE `EventComments` (
`CommentID` int(11) NOT NULL AUTO_INCREMENT,
`EventID` int(11) NOT NULL,
`OwnerID` int(11) NOT NULL,
`Comment` varchar(512) NOT NULL,
`DateTime` datetime NOT NULL,
PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;
I'm trying to get the value of the CommentID field.
So, here is the php code that issues the insert query and then attempts to get the CommentID value.
<?php
session_start();
ob_start();
include_once 'lib/functions.php';
if(isset($_SESSION['uid'])) {
$eventID = $_GET['evid'];
$ownerID = $_SESSION['uid'];
$comment = $_GET['comment'];
$comment = trim($comment);
$dateTime = date('Y-m-d H:i:s');
$db_connection = database_connect();
if($eventID != null && !empty($comment)) {
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";
mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));
$id = mysql_insert_id();
$commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime, $id);
echo $commentHtml;
}
}
ob_end_flush();
?>
This code issues the following error in the php logs:
mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...
I also tried explicitly passing the database link. But that gives the following error:
mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...
As a final note, the insert query works. It is definitely inserting a new row with the expected data!
Any insight here would be appreciated!
Thanks

You are using the mysqli extension to connect and run your query, but then you use the mysql (notice the lack of i at the end) extension to get your inserted id, that can't work. While they are both extensions that provide access to mysql, they are also two very different libraries and can't share a connection between each other.
For the record, mysqli is the one you should be using, mysql is the "old" version that does not support new features of mysql >= 4.1
In other words, the solution is to use mysqli_insert_id()
Also, please escape your parameters properly, you can't put the content of $_GET and $_POST variables inside your query unsecured like that. At the very least use mysqli_real_escape_string()
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . mysqli_real_escape_string($eventID)." [...]
For more infos on this, have a look to the numerous questions on this subject, for example this one: How to properly escape a string via PHP and mysql

You probably want to use the mysqli extension equivalent: mysqli_insert_id()
It might work as it is by passing the connection resource but even if it did, it's not good to mix methods from two separate connection classes:
$id = mysql_insert_id($db_connection);

DATETIME is a Data Type in MySQL that's why INSERT query is not working. Use backtick ` instead.
$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";

Related

Error while doing PHP mysqli insert into table

I have table column log_id as primary_key auto_increment.
Do I need to specify it within INSERT INTO statement or no?
I am getting next error while trying to insert values into my database:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e4' at line 1 INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e44967889b4382ff69fd','93.142.54.135','2018-11-23 14:06:15','1402')
My code is:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
Table structure:
Field Type Null Key Default Extra
log_id int(11) NO PRI NULL auto_increment
log_session varchar(42) NO MUL NULL
log_ip varchar(15) NO NULL
log_vrijeme datetime NO MUL NULL
log_model int(11) NO MUL NULL
Thank you for help.
You should put my_log right after INSERT INTO:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
However, your code has several drawbacks, I'll describe them a bit later.
1. Don't pass unescaped variables into query
Until you have no other way. Use mysqli_real_escape_string($con, $your_var) to prevent SQL injection and using PDO would make it even better.
2. Use HEREDOC syntax to ensure query consistency during future edits
In this way even if you of someone will put " into query it would still work as expected.
3. Omit closing tag on the end of your PHP files if you don't have any content below
This will prevent surprising errors from happening.
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$con = mysqli_connect("localhost","user","password","databse");
$log_session = mysqli_real_escape_string($con, $_SESSION['compare_hash']);
$log_ip = mysqli_real_escape_string($con, $_SERVER['REMOTE_ADDR']);
$log_vrijeme = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
$log_model = mysqli_real_escape_string($con, "1402");
$sql = <<<SQL
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('${log_session}','${log_ip}','${log_vrijeme}','${log_model}')
SQL;
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);

Listing username with bid items - PHP

I'm fairly new to PHP and I'm trying to make a simple auction website. I think I've run into my first problem.
What I'm trying to do is let a registered user add an item to the auction. I can do this just fine. However, I also need to keep track of the user that put the item up for bidding. I thought I could get the accountid by inserting the accountid from the current session into my table, but I keep getting an error saying accountid is an unknown column in my field list.
Here is the code where I create the table.
$sql = "CREATE TABLE biditems (
itemid INT(100) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
accountid INT(100),
biditem VARCHAR(30) NOT NULL,
biddesc tinytext
)";
And to add the items.
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('$accountid', '$item', '$description')";
Your query looks fine. I have also tested it.
Did you double check that the structure of your table is correct?
If you can insert a row via phpMyAdmin or the MySQL Workbench try this and afterwards run a select query like
$rows = "SELECT * FROM biditems";
while ($row = mysql_fetch_array($rows)) {
var_dump($row);
}
Something like this just to make sure.
You should make some sql injection escape first. And if you did it - you should add the variables properly. I did not wrote you some injection escape. You can see sprintf instructions for example.
<?php
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('" . $accountid . "', '" . $item . "', '" . $description . "')";

MySQLI Insert not working not inserting blocked IP

I have this code to insert new attempts to login so when people fail 7 times they get blocked. The problem is when trying to insert while IP is not listed on DB it just does not insert and I cannot understand why. Here is the code:
session_start();
$blocked = mysqli_query($db, "
SELECT * FROM `blocked` WHERE `ip` = '" . $_SERVER["REMOTE_ADDR"] . "' LIMIT 1");
if (mysqli_num_rows($blocked)==0){
$insert = mysqli_query($db, "
INSERT INTO `blocked` VALUES ('', '" . $_SERVER["REMOTE_ADDR"] . "', '1')");
}
I get error
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
if $db was defined somewhere else, it might not be available.
There are ways to get variables to move around in different scopes, otherwise just connect again at the top of this script
$db = connect(...)

Error in SQL INSERT INTO query

I have following code written in PHP:
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Values of $uid and ip() are correct, you can trust me.
Structure of logowania table:
1 idlogowania int(11)
2 user int(11)
3 udane tinyint(1)
4 data timestamp on update CURRENT_TIMESTAMP CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
5 ip text utf8_polish_ci
I don't know where is the error in the statement. MySQL gives:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''user','udane','ip') VALUES (1,0,'79.184.7.44')' at line 1
I tried to debug that, but without successful ending. I know that could be very simple mistake, but human's vision isn't infallible...
Use back ticks for column name,otherwise they are treated as strings.
(`user`,`udane`,`ip`)
Take out '' from the column names.
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
should be
$q = mysql_query("INSERT INTO logowania (user,udane,ip) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
OR use back-tics for the col names
$q = mysql_query("INSERT INTO logowania (`user`,`udane`,`ip`) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Alternative version:
$q = mysql_query("INSERT INTO logowania SET `user` = '" . $uid . "', `udane` = 0, `ip` = '" . ip() . "'"); echo mysql_error();

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