I read some of the answers here and get "mind-locked". I am new and don't work at this, just taught myself over the last 43 years. I converted a piece of code from the hit counter I wrote the other day, and it simply counts the number of times an IP runs my denied access page. The code checks to see if the IP is already in the database table (unique). If it is, it simply increments and updates. If it isn't there, it inserts it with a value of 1.
All was well, then I noticed no increment when testing. So I isolated it and found that it won't recognize the table column value to update it, and it throws an exception when it tries to insert it as a new value because it is unique.
I have looked and looked and cannot seem to understand why it works fine in my hitcounter, but fails miserably here?!?
$IP = $_SERVER['REMOTE_ADDR'];
$IP = preg_replace('#[^0-9\.]#','',$IP);
$db_table = 'deniedcounter';
echo 'Enter denied_record.php<br />';
//$IP = str_replace('.','x',$IP);
function setdeniedcounter($IP, $db_handle, $db_table){
$hits = null;
$ip = "'".$IP."'";
try{
echo "SELECT * FROM $db_table WHERE ip = $ip".'<br />';
$stmt = $db_handle->query("SELECT * FROM $db_table WHERE ip = $ip");
$row_count = $stmt->rowCount();
echo $row_count.' = Rows selected.<br />';
}
catch(PDOException $e){
db_exception_handler($e);
}
if($row_count == 1){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['ip'].' '.$row['hits'].'<br />';
$hits = $row['hits']; $ip = $row['ip'];
$hits++;
try{
$stmt = $db_handle->prepare("UPDATE $db_table SET hits=? WHERE ip=?");
$stmt->execute(array($hits, $ip));
$affected_rows = $stmt->rowCount();
echo $affected_rows.'<br />';
}
catch(PDOException $e){
db_exception_handler($e);
}
exit();
}
elseif($row_count == 0){
$hits = 1;
try{
$stmt = $db_handle->prepare($sql = "INSERT INTO $db_table(ip, hits) VALUES(?, ?)");
$stmt->execute(array($ip, $hits));
$affected_rows = $stmt->rowCount();
//echo $affected_rows.'<br />';
}
catch(PDOException $e){
db_exception_handler($e);
}
}
//echo 'Hits = '.$hits.'<br />';
if(isset($hits)){return $hits;}
}
$db_handle = db_OPEN($db_host, $db_name, $db_username, $db_pwd);
if(strlen($IP) > 6){$da_hits = setdeniedcounter($IP, $db_handle, $db_table);}
if(!isset($da_hits)){$da_hits = setdeniedcounter('ALERT', $db_handle, $db_table);}
$db_handle = db_CLOSE($db_handle);
echo 'Exit denied_record.php<br />';
exit();
====================
OUTPUT:
Enter denied_record.php
SELECT * FROM deniedcounter WHERE ip = '127.0.0.1'
0 = Rows selected.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ''127.0.0.1''
for key 'ip'
Exit denied_record.php
Mysql has a special operator for you.
No need for SELECT first - just INSERT with some extra code:
INSERT INTO $db_table(ip, hits) VALUES(?, ?) ON DUPLICATE KEY UPDATE hits=hits+1
So, your function actually have to be
function setdeniedcounter($ip, $db_handle, $db_table) {
$sql = "INSERT INTO $db_table(ip, hits) VALUES(?, 1)
ON DUPLICATE KEY UPDATE hits=hits+1";
$stmt = $db_handle->prepare();
$stmt->execute(array($ip));
}
bu if you want hits returned - you need to select them though
The problem is you're checking two differnt things. When you use the prepared statement question mark, MySQL inserts its own single quote. So what you check initially is if 127.0.0.1 is there, which it isn't. Then you try to insert '127.0.0.1' (including single quotes in the value), which is already there, which is why it fails.
The IP field in database is a string. Probably in the first sql statement you must use quotes?
$db_handle->query("SELECT * FROM $db_table WHERE ip = $ip");
Replace with:
$db_handle->query("SELECT * FROM $db_table WHERE ip = '".$ip."'");
Related
I am trying to count number of the e-mail addresses in a database that are same as the one acquired by a POST method. But it seems this code cannot count the number correctly, and returns a blank space instead. Is there something wrong in my PHP code? Thank you for taking your time.
<?php
require_once('PHP/function.php');
$mail = $_POST['email'];
$sql = "select count(*) as num from `xxxx` where `mail` = '{$mail}' ;";
$count = mysqlPDO($sql);
$count = $count[0]["count(*)"];
echo "number of the same email adress:\n".$count;
?>
function.php is below;
<?php
function mysqlPDO($sql){
$dsn = 'mysql:dbname=aaaaa;host=localhost';
try{
$dbh = new PDO($dsn,'xxx','zzzzzzz');
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt = $dbh -> query("SET NAMES utf8;");
$stmt = $sth= $dbh->prepare($sql);
$sth->execute(array());
$result=$sth->fetchall(PDO::FETCH_ASSOC);
}catch (PDOException $e){
$result = "error";
}
return $result;
}
?>
I'm not familiar with the PDO method of doing things. But based on the research I've done after you execute the SELECT statement $sth->fetchColumn(); should return the number of rows matching the $_POST email address.
$count = $sth->fetchColumn();
I have a high scores table for a game hosted on this webhost. I'm using PHP with sqlite pdo extensions to have access to the database. I can't seem to figure out what is happening to the database, as the query is not being inserted into the database. I know that the
database is working and can be read from as I can get results out of the
database. I get no output on the webpage saying something is wrong.
Additionally, I've tried a couple of differint methods of sending the query like with $dbConn->query("Select * from something;");.
include_once("Includes/connectDB.php");
$level = $_POST['level'];
$name = $_POST['name'];
$score = $_POST['score'];
$salvage = $_POST['salvage'];
$asteroids = $_POST['asteroids'];
$diff = $_POST['diff'];
if(($level > 0) and ($level <= 5))
{
// make sure table exists
$tbName = getHiS_Tb_Name($level);
// insert data
$sql = "Insert into $tbName (NAME, SCORE, SALVAGE_COLLECTED, ASTEROIDS_DESTROYED, DIFFICULTY)
Values(:name , :score, :salvage, :asteroids, :diff);";
try{
$stmt = $dbConn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':score', $score);
$stmt->bindParam(':salvage', $salvage);
$stmt->bindParam(':asteroids', $asteroids);
$stmt->bindParam(':diff', $diff);
$stmt->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
}
This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I'm going to insert about 500 records in a table using one query :
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`)
VALUES ('val1','val2') ('val3','val4') ... ";
// php_mysql_insert_function
How can I find out haw many rows are inserted in after executing query ?
The answer is affected_rows
$db = new mysqli('127.0.0.1','...','...','...');
$sql = "INSERT IGNORE INTO Test (id,test) VALUES (1,2),(1,3),(2,2),(3,4)";
$ins_test = $db->prepare($sql);
$ins_test->execute();
echo $db->affected_rows;
In this example Test has 2 columns id and test (both integer) and id is the primary key. The table is empty before this insert.
The programm echos 3.
Try this:
Procedural style of coding:
<?php
$host = '';
$user = '';
$password = '';
$database = '';
$link = mysqli_connect($host, $user, $password, $database);
if(!$link)
{
echo('Unable to connect to the database!');
}
ELSE {
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`) VALUES ('val1','val2'), ('val3','val4')";
$result = mysqli_query($link, $sql);
echo mysqli_affected_rows($link);
}
mysqli_close($link);
?>
mysqli_affeccted_rows counts the number of inserts. I think that #wikunia's answer will probably yield the same result. I was in the process of answering you question, before wikunia beat me to it. I place it anyway.
I'm trying to generate a unique username that is not already in my database and then add it as a primary key into my InnoDB database table plus some other field entries.
I get the error code:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'ft6888' for key 'PRIMARY'
Checking the database table manually I can see that it does not already contain the value I'm passing and by echoing the username values I'm binding I can see each is only bound once. The field is not set to auto_increment as in some of these questions but it used as a foreign key in some other tables (but the values I'm binding don't exist in those either).
If I echo out the variables I'm binding just before I bind them I get two sets of correct data. When I insert this same data (copy and pasted) into the table using phpmyadmin it works fine no errors. I can only assume my code itself is somehow trying to insert twice?
$query = "INSERT INTO user_login (username, usertype, hashedpassword) VALUES";
$qPart = array_fill(0, count($excelData), "(?, ?, ?)");
$query .= implode(",",$qPart);
$sth = $dbh->prepare($query);
$i = 1;
$sql = "SELECT username FROM user_login WHERE username = :username";
$sthUser = $dbh->prepare($sql);
Foreach($excelData As $Row){
Do{
//Create unique userID
$finitial = substr(addslashes(str_replace(" ","",$Row['0']['2'])),0,1);
$sinitial = substr(addslashes(str_replace(" ","",$Row['0']['3'])),0,1);
$username = strtolower($finitial).strtolower($sinitial).rand(999,9999);
try {
$sthUser->bindParam(':username', $username);
$sthUser->execute();
$Row = $sthUser->fetch(PDO::FETCH_ASSOC);
}catch (PDOException $e) {
print $e->getMessage();
}
}while(!empty($Row));
$hashedPassword = create_hash($Row['0']['1']);
$usertype = 'Student';
$sth->bindParam($i++, $username);
$sth->bindParam($i++, $usertype);
$sth->bindParam($i++, $hashedPassword);
}
try {
$sth->execute();
}catch (PDOException $e) {
print $e->getMessage();
}
Found the answer here - It seems that bindParam inside the loop binds by reference and is only evaluated at execute statement so it always contains the last bound value for each field.
Changing it to bindValue worked.
I have a simple script which I have included here. the select query works fine but the insert query fails. I am running php, apache and mysql on my macbook.
The table city_profile has ID as a auto increment primary key. And name is a non-null.
function testMySQL() {
$db = new mysqli('localhost', 'root', NULL, 'citee');
//$query = "select * from city_profile"; //this query works
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
//whereas the above one fails..
$results = $db->query($query);
if($results) {
echo '<p>The query is successful.</p>';
}else {
echo '<p>The query is NOT successful.</p>';
}
//close the connection
$db->close();
}
try to change this line:
$query = "insert into city_profile ('name','state','country') values ('charlotte','north carolina','usa')";
into this:
$query = "insert into `city_profile` (`name`,`state`,`country`) values ('charlotte','north carolina','usa')";