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(...)
Related
public function save($itemId, $invoiceName)
{
$query = "
INSERT INTO invoice (item_id, invoice_name)
VALUES (" . $itemId . ",'" . $invoiceName . ")
";
$connection = $this->entityManager->getConnection('master');
return $connection->executeQuery($query);
}
Error while trying to insert into table:
An exception occurred while executing ' INSERT INTO invoice (item_id, invoice_name) VALUES (10600029,'FV/1823/06/2018/SOL') ': SQLSTATE[HY000]: General error: 1290 The MySQL server is running with the --read-only option so it cannot execute this statement
Checked connection to DB its fine.
Tried to save something with same user with a DBeaver DB client and it went through all fine - saved without any problem.
you need to close the connection used before to change connection and insert I think, try something like this:
$connection = $this->entityManager->getConnection()->close();
$query = "
INSERT INTO invoice (item_id, invoice_name)
VALUES (" . $itemId . ",'" . $invoiceName . ")
";
$connection = $this->entityManager->getConnection('master');
return $connection->executeQuery($query);
Even tho I specified 'master' the request was catched by slave all the time.
$entityManager->getConnection()->prepare('INSERT ... ')->execute();
Appeared to fix the problem.
Here's the table structure
CREATE TABLE IF NOT EXISTS `result` (
`res_id` int(11) NOT NULL AUTO_INCREMENT,
`s_id` int(10) NOT NULL,
`i_id` int(6) NOT NULL,
`r_status` text NOT NULL,
`r_score` decimal(6,0) NOT NULL,
PRIMARY KEY (`res_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I've searched for a solution and have tried on different occasions, building the table from scratch, drop and import it back, checked the index. As you can see, I've renamed the id to res_id but when I run it on the browser the error still shows r_id.
If it makes a difference, when the id is not set to auto increment, the same error pops up.
Here's the code snippet for the page where I want to insert into the database.
//retrieve existing r_id
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
//echo "<br>Result: " . $resid_count;
// insert result to table
$sql_result = "INSERT INTO result (res_id, r_score, s_id, i_id) VALUES ('" . $resid_count . "', '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
mysql_query($sql_result) or die ("Error: " . mysql_error());
EDIT: I changed the code like you guys suggested. Took the res_id out from the INSERT. It still says duplicate entry for r_id. I went ahead for trial and error and created another table 'score' with the same structure to replace 'result'. Was wondering if the same table name was giving it problem (could running the page many times cause this?). Same outcome with the score table.
Any help would be greatly appreciated. I'm stuck here and cannot proceed with my project. Thanks.
Atikah
Since res_idis AUTO_INCREMENTI suggest that you replace your insert query by this:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ('". $correct . "', '" . $id . "', '" . $ins_id . "')";
try this
$sql_result = "INSERT INTO result ( r_score, s_id, i_id) VALUES ( '" . $correct . "', '" . $id . "', '" . $ins_id . "')";
res_id will be automatically inserted without your inserting
EDIT.
If you want just insert then you dont need those lines , just remove them, because you are using them for knowing the last res_id . since res_id as i said before its auto_increment. it will increment automatically
$sql_res = "SELECT res_id FROM result ORDER BY res_id DESC LIMIT 1";
$query_res = mysql_query($sql_res) or die("MySQL Error: " . mysql_error());
$data_res = mysql_fetch_assoc($query_res);
$resid_count = $data_res['res_id']+1;
Make sure you don't use apostrophes in your SQL where you use numerics (int). This could cause trouble. And res_id should not be involved at all, because that's the point with having autoincremental columns (You don't have search for the next id in the database with PHP-code, DB takes care of that)
Your code could be translated into two lines:
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES (" . $correct . ", " . $id . ", " . $ins_id . ")";
mysql_query($sql_result) or die ("Error: " . mysql_error());
OR (variables inside quotes gives the actual values)
$sql_result = "INSERT INTO result (r_score, s_id, i_id) VALUES ($correct, $id, $ins_id)";
mysql_query($sql_result) or die ("Error: " . mysql_error());
and of course - don't use mysql_* - functions, cause they're deprecated. Use PDO or Mysqli instead with parameters so you could avoid SQL injection in a safe way. The code you've got is vulnerable to SQL injections.
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
My insert statement for sure does insert the record however mysql_insert_id() keeps returning 0. It should not be this way because there is an auto incremented primary key in that events table and that is running fine as well. Any suggestions on how to get the last inserted ID?
Your query is executed via mysqli, so the mysql function would not hold the inserted ID. Instead, use the mysqli version:
$id = $mysqli->insert_id;
Becasue you are using mysqli and not mysql,
Simply replace mysql_insert_id() with mysqli_insert_id() if using Procedural style
Or replace it with $mysqli->insert_id if using Object Oriented Style
Since you are using mysqli extension, change
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
to
$tSQL = "update events set url = \"details.php?\"" .$mysqli->insert_id. " where idevents = \"$eventid\"";
Because your are using mysqli which is an improvement version of mysql.
Use mysqli->insert_id instead of mysql->insert_id()
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$lastInsId=$mysqli->insert_id();
$tSQL = "update events set url = \"details.php?\"" . $lastInsId . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
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 ."')";
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.