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();
}
}
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 stored procedure in SQL Server 2014 that takes two integers as input and returns an integer. Below is the code to create the stored procedure:
CREATE PROCEDURE [dbo].[p_MergePerson_AuditLog_CheckLogForDuplicate]
#Person1_ID INT,
#Person2_ID INT,
#RowCount INT OUTPUT
AS
SET NOCOUNT ON
SELECT
#RowCount = COUNT(mpal.Transaction_ID)
FROM
MergePersonAuditLog mpal
WHERE
#Person1_ID = #Person2_ID
AND #Person2_ID = #Person1_ID
RETURN #RowCount
Basically, it just takes two ids and sees if a comparison has been made before, just in a different order. Below is the PHP code:
// Connecting to DB
try {
$conn = new PDO("sqlsrv:server=IP;Database=DB", "user", "pwd");
}
catch(PDOException $e) {
die("Error connecting to server $e");
}
// Arrays that will hold people IDs
$person1Array = array();
$person2Array = array();
// Holds the row count used to see if a comparison has already been performed
$rowcount = 5; // Setting to 5 to make sure the stored procedure is actually setting the value.
// Query to get the people that will be compared
$query = "SELECT p.PersonID
FROM Person p
WHERE (p.StudentNumber IS NULL OR p.StudentNumber = '')
AND (p.StaffNumber IS NULL OR p.StaffNumber = '')
ORDER BY
p.PersonID";
$stmt = $conn->query($query);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach ($row as $key => $value) {
$person1Array[] = $value;
}
}
$person2Array = $person1Array;
// Begin the comparisons
print "Beginning the comparisons <br>";
foreach ($person1Array as $person1id) {
foreach ($person2Array as $person2id) {
print "Checking $person1id and $person2id <br>";
if ($person1id != $person2id) {
print "Not the same. Continuing.<br>";
// Checking to see if the comparison has already been made
$query = "{? = call p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?)}";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $rowcount, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,4);
$stmt->bindParam(2, $person1id, PDO::PARAM_INT);
$stmt->bindParam(3, $person2id, PDO::PARAM_INT);
$stmt->execute();
print $rowcount . "<br>";
}
}
}
print "FINISHED! <br>";
$stmt = null;
$conn = null;
?>
When I run this code, 5 is still being printed for $rowcount even though it should be set to 0 by the stored procedure. If the value is 0, more code will be executed that I didn't include, but I want to get this part right first. Running the procedure in management studio works fine. Can someone tell me why $rowcount is not getting updated? I am running php 5.6 on Windows 10.
Ok, I found an answer that worked for me. I read https://msdn.microsoft.com/en-us/library/cc626303(v=sql.105).aspx which doesn't have anything to do with PDO_SQLSRV, but with sqlsrv_connect(). In that article, it stated the last parameter was the output parameter. I changed my code to look like this:
// Checking to see if the comparison has already been made
$query = "{call p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?, ?)}";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $person1id, PDO::PARAM_INT);
$stmt->bindParam(2, $person2id, PDO::PARAM_INT);
$stmt->bindParam(3, $rowcount, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,4);
$stmt->execute();
print $rowcount . "\n";
Basically, I moved the "?" From the beginning of the call statement to the end and moved the bindParam to the end as well. That seems to have done the trick.
You could get the return value via a select statement:
$query = "select p_MergePerson_AuditLog_CheckLogForDuplicate(?, ?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $person1id, PDO::PARAM_INT);
$stmt->bindParam(2, $person2id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchColumn();
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I need some help here. I am working on an export from Salesforce to MySQL database.
I may be choosing the wrong path here as I am a novice in both. What I have right now is a simple php query to our Salesforce. The query right now just echos the results to HTML. What I need to do is have this script connect to a MySQL database and add or update the records in the database.
Using the Salesforce PHP Toolkit my connection and query is this simple bit. (Appologies for the ugly inline html.
$query = "SELECT Id, FirstName, Random_Last_Initial__c, Created_Date__c, Building_Zip_Code__c from Lead";
$queryResult = $mySforceConnection->query($query);
$records = $queryResult->records;
foreach ($records as $record) {
$sObject = new SObject($record);
echo "<ul style='list-style:none;'>";
echo "<li>Id = ".$sObject->Id;
echo "</li><li>First Name = ".$sObject->fields->FirstName;
echo "</li><li>Initial = ".$sObject->fields->Random_Last_Initial__c;
echo "</li><li>Date Created = ".$sObject->fields->Created_Date__c;
echo "</li><li>Zip = ".$sObject->fields->Building_Zip_Code__c;
echo "</li></ul>";
}
All of that is fine, i just need to dump the results into the database.
Thanks!
Should work
$dbh = New PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
foreach ($records AS $record)
{
$sObject = New SObject($record);
$stmt = $dbh->prepare ("INSERT INTO tablename SET sObjectId = :sid, firstName = :firstName, initial = :initial, createdDate = :created, zipCode = :zipcode");
$stmt -> bindParam(':sid', $sObject->Id);
$stmt -> bindParam(':firstName', $sObject->fields->FirstName);
$stmt -> bindParam(':initial', $sObject->fields->Random_Last_Initial__c);
$stmt -> bindParam(':created', $sObject->fields->Created_Date__c);
$stmt -> bindParam(':zipcode', $sObject->fields->Building_Zip_Code__c);
$stmt -> execute();
}
Just fill out your database settings, table name, and column names as appropriate
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."'");