I´m trying to create just one new row in a MySQL table
The problem is that I´m getting two new rows in my database.
I really can´t see why this is happening. The debug_to_console( "makepass" ); - my debug function - only gets executed once? AND the two rows it creates is not identical/copies
debug_to_console( "makepass" );
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($salt);
$makepassJBH = '';
for ($i = 57; $i < $len; $i ++) {
$makepassJBH .= $salt[mt_rand(0, $len -1)];
}
$newpassJBH = password_hash($makepassJBH, PASSWORD_BCRYPT );
$licensidentifierJBH = '';
for ($i = 57; $i < $len; $i ++) {
$licensidentifierJBH .= $salt[mt_rand(0, $len -1)];
}
$fullkey = $makepassJBH . $licensidentifierJBH;
try {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Insert columns.
$columns = array('licenskey','licenskey_Identifier','dateCreated', 'printed');
// Insert values.
$values = array($db->quote($newpassJBH), $db->quote($licensidentifierJBH), $db->quote(date("Y-m-d")), $db->quote(0));
// Prepare the insert query.
$query
->insert($db->quoteName('#__licenskey'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('licenskey_Identifier') . ' = VALUES(' . $db->quoteName('licenskey_Identifier') . ')';
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
echo $db->replacePrefix((string) $query);
$db->execute();
}
The SQL dump:
INSERT INTO `mdh_licenskey` (`licenskey`,`licenskey_Identifier`,`dateCreated`,`printed`) VALUES ('$2y$10$jXkjJX1OZ7Vu0okV/QlxcehF5T2SSPZFhVHIx.E64HhidgYY.3URS','juLEo','2018-07-23','0') ON DUPLICATE KEY UPDATE `licenskey_Identifier` = VALUES(`licenskey_Identifier`)
Since the license key is generated by the PHP code above, that code must be executed twice. This can happen for multiple reasons but it can be difficult for us to guess exactly why. Either check if your browser is calling it twice, or if it is called twice from within the PHP code.
Make sure your script isn't executed twice. I had this issue when using firebug for example. This plugin made my page execute twice but not outputting to the console.
Sort of like a "prefetch" of the page before showing, don't know for sure.
Maybe add a 'debug to console' point on every line, like 'here 1, here 2'..
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
I'm trying to run a SQL query, and it is working correctly in phpMyAdmin, but whe running it in PHP, the query comes back very wonky. The following query yields two different results:
SELECT `stock_ticker`, `stock_simpleName`, `stock_logo`
FROM `stocks`
WHERE stock_simpleName REGEXP'^c'
I get the following results in phpMyAdmin (Which is correct):
stock_simpleName
----------------------
Coca-Cola
Campbell's
ConAgra Foods
However, in PHP it comes out really weird:
stock_simpleName
-----------------------
Coca-Cola
MasterCard
Campbell's
Microsoft
The Walt Disney Company
PepsiCo
The Hershey Company
Proctor & Gamble
ConAgra Foods
...etc...
Why is this happening? This doesn't make any sense. Is it due to a server setting in PHP or some form of encoding or whatnot?
EDIT:
Here is my PHP Code:
The sub-model class (the creator of the pieces):
public function allOtherSearchResults($query, $dontQuery = null) {
$name = "stocks";
$where = "stock_simpleName REGEXP'^" . $query . "'";
$cols = array("stock_ticker", "stock_simpleName", "stock_logo");
$limit = 5;
return $this->select($name, $cols, $where, $limit);
}
The main-model class (this runs the query):
public function select($tableName, $columns, $where = null, $limit = null) {
global $purifier;
// Make columns SQL friendly
$cols = "`";
$cols .= implode("`, `", $columns);
$cols .= "`";
$table = "`" . $tableName . "`";
if (!empty($where)) {
$where = " WHERE " . $where;
}
// Check limit
if (!empty($limit)) {
$limit = " LIMIT $limit";
}
// SQL CODE
$sql = "SELECT " . $cols . " FROM " . $table . $where . $limit;
// SQL DEBUGGING IF CODE RETURNS BOOLEAN ERROR
echo $sql . "<br>";
$query = $this->conn->query($sql);
// Store the value in a variable called table with an array of that table's name followed by it's values
// EX: $model->table["bands"]["band_name"]
//
// Accessible by the individual page/directory's controller's
while($row = $query->fetch_assoc()){
// Store values as $model->table["tableName"]["columnName"]["index (usually 0)"]
foreach ($row as $key => $val) {
$this->data[$tableName][$key][] = $row[$key];
}
}
// Loop through results to clean them
// Foreach loops through each column
// Make sure the table isn't empty (i.e. login returns an error)
if (!empty($this->data[$tableName])) {
foreach ($this->data[$tableName] as $key => $tableArray) {
// For loop goes through each value in a certain row
for ($i = 0; $i < count($tableArray); $i++) {
// Convert from data variable to table after HTML PURIFIER
$this->table[$tableName][$key][$i] = $purifier->purify($tableArray[$i]);
}
}
}
// Declare the array after loop has finished for use in view
$this->table;
if (!empty($this->table)) {
return true;
}
}
And it gives me the same SQL output as above. I am not sure if there is a different interpretation of certain characters in PHP versus the standard MySQL in phpMyAdmin. Has anyone even had this problem before?
I'm guessing, that there is a problem wiht ^ character.
Try to set proper connection & result encoding, eq.
$this->conn->query("MYSQL SET NAMES utf8");
$this->conn->query("MYSQL SET CHARACTER SET utf8");
Also, check if your php script file is saved in UTF-8 encoding.
Moreover, you should consider of using prepared statement (even to prevent SQL Injection):
$this->conn->prepare("SELECT * FROM `stocks` WHERE `stock_simpleName` REGEXP ?");
$this->conn->bind_param("s", "^c");
$this->conn->execute();
$query = $this->conn->get_result();
I am trying to update an MS Access table using an array here is my code
for($i = 1; $i<=$rows; $i++)
{
$seedsize[$i] = $_POST['packageType'.$i];
$RefNo[$i] = $_POST['field'.$i];
(int)$qtyOrder[$i] = $_POST['ordered'.$i];
(int)$qtyDel[$i] = $_POST['delivered'.$i];
$unitPrice[$i] = $_POST['unitPriceDtl'.$i];
$ref2[$i] = $_POST['grade'.$i];
//$date[$i] = $_POST['myDate'.$i];
}
$InvoiceID = $_SESSION['InvoiceID'];
$sql = "UPDATE
[Tbl_Invoice_Details]
SET
[Seed Size]=?,
[RefNo]=?,
[Quantity Ordered]=?,
[Quantity Delivered]=?, [Ref2]=?,
[PricePerUnit]=?
WHERE
[Invoice_ID]=?";
$data = $conn2->prepare($sql);
for($x = 1; $x <= 4; $x++)
{
$data->execute(array($seedsize[$x], $RefNo[$x], $qtyOrder[$x], $qtyDel[$x], $unitPrice[$x], $ref2[$x], $InvoiceID));
echo $RefNo[$x]."<br/>";
}
I am getting this error "Invalid character value for cast specification: -3030 [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression."
Thank you for your help!
Have you confirmed that there isn't any null values in the data? Null values might be causing the cast error.
I would suggest to cast all numeric values:
for($i = 1; $i<=$rows; $i++)
{
$seedsize[$i] = $_POST['packageType' . $i]; // Not sure about this one
$RefNo[$i] = (int)$_POST['field' . $i];
$qtyOrder[$i] = (int)$_POST['ordered' . $i];
$qtyDel[$i] = (int)$_POST['delivered' . $i];
$unitPrice[$i] = (float)$_POST['unitPriceDtl' . $i];
$ref2[$i] = $_POST['grade' . $i]; // Not sure about this one
//$date[$i] = $_POST['myDate' .$i];
}
Please note that the cast should be on the right side of the assignment operator.
Why is 4 hard coded in the 2nd for loop? Just curious.
What I think is the issue is(int)$qtyOrder[$i] or (int)$qtyDel[$i] or really anything else. The error is saying the data it expected to get is not what it got, so somewhere you sent ABC when it wanted only 123 (Numbers) for example. You should do any processing on the POST'ed information, maybe somting like:
$qtyOrder[$i] = intval($_POST['ordered'.$i]);
$qtyDel[$i] = intval($_POST['delivered'.$i]);
I've never done what your doing percisly but I think this will send you on the right track. Here is the PHP manual page I looked at.
I got something like this.
It's working, but have to do a mysql query like 40 times is not the best thing.
Can somebody help me get it in to one query?
$string_unique = 'Unique string';
$number = count($something);
for ($i=0; $i < $number; $i++)
{
if(!empty($some_input)) {
$string_one = 'Something_one' . $i;
$string_two = 'Something_two' . $i;
mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
} else {
$string_one = '';
$string_two = '';
mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
}
You can generate a single query in that loop and then execute it only once:
$query = 'INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES ';
$queryValues = array();
$string_unique = 'Unique string';
$number = count($something);
for ($i=0; $i < $number; $i++)
{
if(!empty($some_input)) {
$string_one = 'Something_one' . $i;
$string_two = 'Something_two' . $i;
$queryValues[] = sprintf('("%s", "%s", "%s")', $unique_string, $string_one, $string_two);
} else {
// I can't understand what are you using this part for... Anyway.
$queryValues[] = sprintf('("%s", "", "")', $unique_string);
}
}
$query .= implode(', ', $queryValues);
// And here is the unique key updating.
// I don't know whole the structure, so I just guess you have the PRIMARY `id` row
// What you did in your ON DUPLICATE KEY was unnecessary.
$query .= ' ON DUPLICATE KEY UPDATE `id`=`id`';
// Don't use mysql_* functions in new code.
// See: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php
mysql_query($query);
You're a allowed to add multiple rows of data in an insert statement in MySQL. That way, you can build one big insert statement in the loop, and execute it in one go after the loop. That is way faster and much more efficient.
You can insert multi row with sql,
here an example
insert into table1 (First,Last) values ("Fred","Smith"),
("John","Smith"),
("Michael","Smith"),
("Robert","Smith");
I am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table.
The checkboxes are posted in an array:
$can = $_POST['can'];
I've created the following loop to dump the variables for the MySQL insert:
for($i=1;$i<8;$i++){
if($can[$i] == "on"){
${"jto_can".$i} = 'Y';
}
else{
${"jto_can".$i} = 'N';
}
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);
This correctly outputs:
YYNYYYY
However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes.
mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));
Can anyone explain why the print_r displays the variables whereas MySQL update does not?
Stick with the array, and form the query dynamically:
$sql = 'UPDATE jto SET ';
$cols = array();
foreach( range( 1, 7) as $i) {
$value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
$cols[] = 'jto_can' . $i . ' = "' . $value . '"';
}
$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';
Now do a var_dump( $sql); to see your new SQL statement.
this is not a mysql problem. mysql will only see what you put into that string. e.g. dump out the query string BEFORE you do mysql_query. I'm guessing you're doing this query somewhere else and have run into scoping problems. And yes, this is lazy. No it's not "smart". you're just making MORE work for yourself. What's wrong with doing
INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...