I use the Paypal IPN. When the user buys articles, I use this code to generate codes they can redeem. However, it's not working:
public function clave(){
$Valores = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$ValorTemporal = "";
for($i=0;$i<10;$i++) {
$ValorTemporal .= substr($Valores,rand(0,37),1);
}
return $ValorTemporal;
}
public function cupon($items){
$mysqli = $this->connection();
for ($i = 1; $i <= $items; $i++) {
$yz= $this->clave();
$sqli.$i = $mysqli->query("INSERT INTO ventas (id_venta, id_usuario,id_producto ,used,cupon) VALUES ('$txn_id','$username','$item_name','$used','$yz')");
}
return true;
}
$items is the number of products
I don't know if I'm using the for() statement correctly.
public function cupon($items){
global $txn_id, $username, $item_name, $used;
$mysqli = $this->connection();
for ($i = 1; $i <= $items; $i++) {
$yz = $this->clave();
$mysqli->query("
INSERT INTO `ventas`
(`id_venta`, `id_usuario`, `id_producto`, `used`, `cupon`)
VALUES
('$txn_id', '$username', '$item_name', '$used', '$yz')
");
}
return true;
}
OR little better
public function cupon($items, $txn_id, $username, $item_name, $used){
$mysqli = $this->connection();
for ($i = 1; $i <= $items; $i++) {
$yz = $this->clave();
$mysqli->query("
INSERT INTO `ventas`
(`id_venta`, `id_usuario`, `id_producto`, `used`, `cupon`)
VALUES
('$txn_id', '$username', '$item_name', '$used', '$yz')
");
}
return true;
}
Related
I am getting Fatal error: Cannot pass parameter 3 by reference in line# 4
please suggest me solution I want the binding part dynamic.
$values = array($username,$password);
$query = "select * from users where email_id = ? and password = ?"
$this->con = new mysqli('localhost', 'username', 'password','dbname');
$stmt = $this->con->prepare($query);
$count = 0;
for ($i = 0; $i < count($values); $i++) {
$stmt->bind_param(++$count,$values[$i], PDO::PARAM_STR,12);
}
if ($stmt->execute()) {
while ($row = $this->stmt->fetch()) {
$data[] = $row;
}
return $data;
} else {
return null;
}
use bindValue()
$stmt->bindValue(++$count,$values[$i], PDO::PARAM_STR,12);
I have an if/else block of code below that is supposed to call a function with specific parameters, depending on the situation. The function updates specific values in the MySQL database. However, the database values are not being updated. What am I doing wrong?
The following is my code:
process.php
$success = false;
$homeScore = $_POST['home'];
$awayScore = $_POST['away'];
$homeTeamName = $_POST['homeTeam'];
$awayTeamName = $_POST['awayTeam'];
try {
$win = 0;
$loss = 0;
// HOME TEAM
if ($homeScore > $awayScore)
{
$win = 1; $loss = 0;
updateStandings($db7, $homeTeamName, $win, $loss);
$win = 0; $loss = 1;
updateStandings($db7, $awayTeamName, $win, $loss);
}
// AWAY TEAM
elseif ($awayScore > $homeScore)
{
$win = 1; $loss = 0;
updateStandings($db7, $awayTeamName, $win, $loss);
$win = 0; $loss = 1;
updateStandings($db7, $homeTeamName, $win, $loss);
}
$success = $_SERVER['HTTP_REFERER'];
}
catch (Exception $e)
{
$success="/error";
}
header("Location: " . $success);
function updateScore($db, $gameID, $home, $away)
{
$db -> updateScoreForGame($gameID, $home, $away);
}
function updateStandings($db, $teamName, $win, $loss)
{
$db -> updateLeagueStandings($teamName, $win, $loss);
}
updateLeagueStandings function
public function updateLeagueStandings($teamName, $win, $loss) {
try {
$sth = $this -> db -> prepare("UPDATE teams SET wins = wins + (:winsNum), losses = losses + (:lossesNum) WHERE Name = `:teamName`");
$sth->bindParam(':winsNum', $win, PDO::PARAM_INT);
$sth->bindParam(':lossesNum', $loss, PDO::PARAM_INT);
$sth->bindParam(':teamName', $teamName, PDO::PARAM_STR);
$sth -> execute();
} catch (Exception $e) {
header('Location: /error');
}
}
What's wrong here? Is the query wrong? I ran the query with substituted values in PHPMyAdmin and it worked fine, so it can't be the query.
WHERE Name = `:teamName`
If this is what exactly in your script, then you need to remove the backtick quote around the variable.
The backticks are used to quote field names.
some extend reading
I have some user uploaded images that can be sorted and need to save the image position. Was thinking that I could do this easy enough by just using the loop index while iterating through them. However using my $i variable to bind the 3rd param is being passed as a reference and I need the value. How do I get around this?
Here's the code:
$postId = $args['postId'];
$images = explode(",", $args['images']);
$sql = 'INSERT INTO post_image (name,postId,ordinal) VALUES ';
$part = array_fill(0, count($images), "(?, ?, ?)");
$sql .= implode(",", $part);
logit($sql);
try{
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$count = count($images);
$n = 1;
for($i = 0; $i < $count; $i++){
$stmt->bindParam($n++, $images[$i]);
$stmt->bindParam($n++, $postId);
$stmt->bindParam($n++, $i);
}
$result = $stmt->execute();
if($result !== false) {
return true;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
I fixed it by using bindValue for the third param.
I found this http://net.tutsplus.com/tutorials/php/the-problem-with-phps-prepared-statements/
and it works really good to have it in a seperate php file which my other files calls to with a query as argument.
Is it possible to make something similar with other queries like insert and update?
This is the updated example:
$params is an array.
function insertToDB($params, $db) { //Pass array and db
$fields = array();
$conn = new mysqli('localhost', 'root', 'root', 'db') or die('XXX');
$stmt = $conn->stmt_init();
$stmt->prepare("SELECT * FROM ".$db);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$fields[] = $field->name;
}
$fields = implode(", ", $fields);
$placeholders = implode(',', array_fill(0, count($params), '?'));
$types = '';
foreach($params as $value) {
$types.= substr(strtolower(gettype($value)), 0, 1);
}
$ins = "INSERT INTO MYDB (".$fields.") VALUES (".$placeholders.")";
$bind_names[] = $types;
for ($i = 0; $i < count($params); $i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
if ($stmt->prepare($ins)) {
call_user_func_array(array($stmt,'bind_param'),$bind_names);
$insresult = $stmt->execute();
}
return $insresult;
$stmt->close();
}
I want to store array into mysql db something like this
item_row = nike,adidas,puma
qty_row = 1,3,2
total_row = 100,200,150
foreach
foreach ($_SESSION['order'] as $values) {
$item_name = $values['item-name'];
$item_qty = $values['item-qty'];
$item_price = $values['item-price'];
}
Let me know how to do that?
update
foreach ($_SESSION['order'] as $values) {
$item_name[] = $values['item-name'];
$item_qty[] = $values['item-qty'];
$item_price[] = $values['item-price'];
}
$item_row = implode(",", $item_name);
$qty_row = implode(",", $item_qty);
$total_row = implode(",", $item_price);
item_row = implode(',', $_SESSION['order']['item-name']);
qty_row = implode(',', $_SESSION['order']['item-qty']);
total_row = implode(',', $_SESSION['order']['item-price']);
I'm using a class to manage the connection to the data base and the query execution let me add it to you:
class DbConnection
{
var $ReturnQuery;
function Connect()
{
$connection = mysql_connect("serverName", "user", "password");
$DbSelect = mysql_select_db("databaseName", $connection);
if ($DbSelect)
return true;
else
return false;
}
function Execute($Query)
{
$ExecuteQuery = mysql_query($Query);
$affected = mysql_affected_rows();
if ($affected != -1)
{
if ($affected != 0)
{
if ($ExecuteQuery != 1)
{
while($row=mysql_fetch_assoc($ExecuteQuery))
{
$ResulArray[] = $row;
}
$this->ReturnQuery = $ResulArray;
}
return 1;
}
else
{
$this->ReturnQuery = '';
return 0;
}
}
else
{
$this->ReturnQuery = '';
return -1;
}
}
}
and then you can create instances to execute your query:
require_once('Includes/DbConnection.php');
$this->db = new DbConnection();
$this->db->Connect();
$query = "insert into items (item_name, item_qty, item_price) values ('".$item_name."', '".$item_qty."', '"$item_price"');
$query_safe = mysql_real_escape_string($query);
$this->db->Execute($query_safe);
I hope it helps!!
foreach ($_SESSION['order'] as $values) {
mysql_query('INSERT INTO tablename (name, qty, price) VALUES("'.$values['item-name'].'", "'.$values['item-qty'].'", "'.$values['item-price'].'"');
}