MySQL Query not updating values in the database in PHP - php

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

Related

Using multi_query doesn't give the desired output

I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();

for() and mysql statement

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;
}

Sql injection without overwrite

I have a php script which fill tables in my sql database. The problem is that it overwrites the tables each time I run it and I just want to add the datas at the end. I took inspiration from an existing script that I modify and I don't understand all it contains.
Here is my code :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
$colMap = array(
0 => "LIBELLE",
1 => "DESCRIPTION",
2 => "CODE"
);
if (isset($_GET['data']) && $_GET['data']) {
$select = $db -> prepare('DELETE FROM COMPETENCES');
$select2 = $db -> prepare('DELETE FROM DESCRIPTION');
$select -> execute();
$select2 -> execute();
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++) {
if (!isset($colMap[$c]) && !isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$select = $db -> prepare('SELECT ID FROM COMPETENCES WHERE ID=? LIMIT 1');
$select2 = $db -> prepare('SELECT ID FROM DESCRIPTION WHERE ID=? LIMIT 1');
$select -> execute(array($rowId));
$select2 -> execute(array($rowId));
if ($row = $select->fetch() && $row = $select2->fetch()) {
$query = $db->prepare('UPDATE COMPETENCES SET `' . $colMap[$c] . '` = :newVal WHERE ID = :id');
$query2 = $db->prepare('UPDATE DESCRIPTION SET `' . $colMap[$c] . '` = :newVal2 WHERE ID = :id2');
} else {
$query = $db->prepare('INSERT INTO COMPETENCES (ID, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION (ID, `' . $colMap[$c] . '`) VALUES(:id2, :newVal2)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query2->bindValue(':id2', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array(
'result' => 'ok'
);
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
}
I thought that remove the DELETE queries will fix the problem but the script doesn't work at all. I think the issue comes from the ids but I don't find where.
The datas are taken from a grid created with the javascript plugin Handsontable.
Can you help me please? I really need this script.
My script still doesn't work but I removed all what I found useless. Now, nothing happens at all in the database even if the new code seems to be more appropriate.
Here is the new :
<?php
try {
session_start();
require_once('./lib/demo/php/functions.php');
$db = getConnection();
mysql_set_charset('utf8', $db);
$colMap = array(
0 => 'LIBELLE',
1 => 'DESCRIPTION',
2 => 'CODE'
);
if (isset($_GET['data']) && $_GET['data']) {
for ($r = 0, $rlen = count($_GET['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_GET['data'][$r]); $c < $clen; $c++){
if (!isset($colMap[$c])) {
continue;
}
$newVal = $_GET['data'][$r][$c];
$query = $db->prepare('INSERT INTO COMPETENCES ("'.$colMap[$c].'") VALUES(:newVal)');
$query2 = $db->prepare('INSERT INTO DESCRIPTION ("'.$colMap[$c].'") VALUES(:newVal2)');
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query2->bindValue(':newVal2', $newVal, PDO::PARAM_STR);
$query->execute();
$query2->execute();
}
}
}
$out = array('result' => 'ok');
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>

PHP prepared statement issue

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);

PDO bind loop index

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.

Categories