Why is my update statement updating my columns with the wrong data? - php

Why is my update statement updating my columns card_id with the wrong data?
My database structure.
$deckCardIds Holds a array of different two digit numbers.
What I expect the code to: Update each column based on the the current row I am looping through and updating card_id with the current index of $deckCardIds.
What is actually happening: The columns are looped through and data is set with $deckCardIds but then set to 0 when the loops moves to the next iteration.
<?php
$playerId=$_GET['playerid'];
$playerDeckCardIds=$_GET['deckcardids'];
$deckCardIds = explode(" ", $playerDeckCardIds);
array_pop($deckCardIds);
try
{
#Connect to the db
$conn = new PDO('mysql:host=localhost;dbname=tcg', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT row_id FROM player_deck WHERE player_id = :player_id');
$stmt->execute(array('player_id' => $playerId));
$r = $stmt->fetchAll(PDO::FETCH_OBJ);
$i=0;
foreach($r as $row)
{
$stmt = $conn->prepare('UPDATE player_deck SET card_id = :card_id WHERE row_id = :row_id');
$stmt->bindParam(':card_id', $deckCardIds[$i]);
$stmt->bindParam(':row_id', $row->row_id);
$stmt->execute();
$i++;
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>

Related

Problem in an Insert : values list are not matching column list

So basically, I have to retrieve the primary keys of two tables which are linked by a multiple association (if the name in the "joueur" table matches the name in the "match_rencontre" table, then i select their IDs. And then I have to insert these keys into the table "participer", to find out who are the players who participated
here is my database, i'm working on xampp, so if you wanna test it : http://www.filedropper.com/wszzzzcebasketsql
The error i get is : "Error : SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 "
I don't want to insert something into "note" and "titulaire" for the moment.
Thanks for your help
<?php
require('database.php');
global $db;
$req = $db->prepare("SELECT joueur.n_license, match_rencontre.id_match_rencontre FROM match_rencontre, joueur, participer WHERE joueur.n_license = participer.n_license AND participer.id_match_rencontre = match_rencontre.id_match_rencontre AND joueur.joue = match_rencontre.nom_equipe_adverse");
$req->execute();
while ($row = $req->fetch()) {
$n_license = (int)$row['joueur.n_license'];
$id_match_rencontre = (int)$row['match_rencontre.id_match_rencontre'];
}
}
try {
$query = "INSERT INTO participer(n_license, id_match_rencontre) VALUES ('$n_license','$id_match_rencontre')";
$go=$db->prepare($query);
$go->execute();
} catch (PDOException $e) {
echo 'Error : ' . $e->getMessage();
}
?>

Having issues with incrementing a field in the database

I've established a database full of movies which is connected to a HTML form of which the information is ported with PHP POST (Acts as a movie database).
When the user enters a search term (Either title, genre, year or classification) the PHP script search.php is handed the information.
This goes fine, however, i also have a column in my DB which is titled times_searched which has a default value of zero.
I feel like one of the big problems is i've just been staring at this file for too long and something simple is not apparent to me right now.
I'm very new to PHP and WebDev in general.
I have tried issuing a second statement to execute inside the foreach loop of the TableRow class and have tried different syntaxes and attempting to bind previous statements to new statements.
class TableRows extends RecursiveIteratorIterator
{
function __construct($it)
{
parent::__construct($it, self::LEAVES_ONLY);
}
function current()
{
return "<td style='width:150px;border:1px solid black;'>" .
parent::current()."</td>";
}
function beginChildren()
{
echo "<tr>";
}
function endChildren()
{
echo "</tr>" . "\n";
}
}
function printAssocArray($stmt)
{
foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll()))
as $k=>$v) {
echo $v;
}
}
require 'Templates/header.php';
//DB variables
$serverName = "localhost";
$userName = "root";
$password = "";
//Post variables
$title = ($_POST['title']);
$year = ($_POST['year']);
$genre = ($_POST['genre']);
$rating = ($_POST['rating']);
if (isset($_POST['submit'])) {
try {
//Create PDO object using DB variables
$conn = new PDO(
"mysql:host=$serverName;dbname=project_db", $userName, $password
);
//Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<h3 class='center'>Connection Successful!</h3>";
if (!empty($_POST['title']) && empty($_POST['genre'])
&& empty($_POST['rating']) && empty($_POST['year'])
) {
$stmt = $conn->prepare(
"UPDATE movies SET
times_searched = times_searched + 1 WHERE id = :id;
IN (SELECT * FROM movies WHERE title LIKE '%$title%'"
);
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindValue(':id', $result['id']);
$stmt->execute();
//Use function call to print information to table using TableRows
printAssocArray($stmt);
}elseif (!empty($_POST['genre']) && empty($_POST['rating'])
&& empty($_POST['year']) && empty($_POST['title'])
) {
$stmt = $conn->prepare(
"SELECT * FROM movies WHERE genre LIKE '%$genre%'"
);
$stmt->execute();
//Collect Result in associative array
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
//Use function call to print information to table using TableRows
printAssocArray($stmt);
}
//New Block
if (!empty($_POST['title']) && empty($_POST['genre'])
&& empty($_POST['rating']) && empty($_POST['year'])
) {
$updateQuery = "UPDATE movies SET times_searched = times_searched + 1
WHERE id IN (SELECT id FROM movies WHERE title LIKE :title)";
$stmt = $conn->prepare($updateQuery);
$stmt->bindValue(':title', "%{$title}%");
$stmt->execute();
$outputQuery = "SELECT * FROM movies WHERE title LIKE :title";
$stmt2 = $conn->prepare($outputQuery);
$stmt2->bindValue(':title', "%{$title}%");
$data = $stmt2->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
foreach ($row as $v) {
echo $v, " ";
}
echo "<br>",\n;
}
The aim is to try and return the requested query from the database then increment the times_searched column before printing it using the TableRow Class, this should happen each time the query is run (if the page is refreshed the times_searched column should increment)
This is being used for completion of a homework project, and security is not nessacarily a factor (though use of PDO was requested).
Your query should either use WHERE id = :id (single movie item) or WHERE id IN (SELECT id FROM movies WHERE title LIKE '%$title%') (multiple movie items), not both, not separated by a ;.
I assume you want to use the latter (update multiple movie items), change
$stmt = $conn->prepare(
"UPDATE movies SET
times_searched = times_searched + 1 WHERE id = :id;
IN (SELECT * FROM movies WHERE title LIKE '%$title%'"
);
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindValue(':id', $result['id']);
$stmt->execute();
to
$stmt = $conn->prepare("UPDATE movies SET times_searched = times_searched + 1 WHERE id IN (SELECT id FROM movies WHERE title LIKE :title)");
$stmt->bindValue(':title',"%{$title}%");
$stmt->execute();
For the // New Block part:
Replace
$outputQuery = "SELECT * FROM movies WHERE title LIKE '%title%'";
$stmt2 = $conn->prepare($outputQuery);
$stmt2->bindValue('title', $title);
with
$outputQuery = "SELECT * FROM movies WHERE title LIKE :title";
$stmt2 = $conn->prepare($outputQuery);
$stmt2->bindValue(':title', "%{$title}%");

echo one before the last table row from my database

this is my code that echo last table row . and i wanna echo one before the last table row together with this code . any body can help ?
i use this to show table parameters in my application
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//creating a query
$stmt = $conn->prepare("SELECT name,family FROM student_list;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result(
$t1,
$t2
);
$list = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['t1'] = $t1;
$temp['t2'] = $t2;
array_push($list, $temp);
}
//displaying the result in json format
echo json_encode($list);
You can use limit to get second last row of table.
SELECT name,family FROM student_list ORDER BY id DESC LIMIT 1,1

How to select multiple records from SQL and insert into a Session

I am looking for how to insert multiple records from a SQL table into a session variable, or into multiple unique session variables.
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
$_SESSION['courseinfo'] = $row;
The table "courses" has a few records inside, all with the teacherID being that of the current userID, defined at the start. When I print_r($_SESSION['courseinfo']); it only displays one of the records in the table.
I'm trying to create a loop that displays all the information grabbed, for each record, since you won't know for sure how many records you'll grab at any given time. Any answers are greatly appreciated!
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
while ($row = $stmt->fetch()):
$row['YourColumn'];
endwhile;
Use while() loop to fetch all record as per your query
You can fetch all your records with changing the fetch -> fetchAll() doc
$rows = $stmt->fetchAll();
Sessions can also store arrays and objects (they get serialized automatically). So you can just store the whole results set there.
$_SESSION['courseinfo'] = $rows;
Side note: Consider using another storage place for all of the returned data, if its a lot, and in the session store only Ids.

Create an array from database results

I want to create an array from a database query. I want to select 10 random questions by their ID, and put them into an Array, JUST the ID, i do not want it to be like [0]=>array('1'),[1]=>array('2'), I would like to to simply be, array('1','2','3') etc.
After they are in the array i would like to be able to check if the id is in the array
If u use the PDO php extension, use the http://www.php.net/manual/en/pdostatement.fetchcolumn.php to retrieve the values of the column as one-dim array.
try {
$pdo = new PDO([dsn], [username], [password]);
$sql = "
SELECT ID
FROM [tablename]
ORDER BY RAND()
LIMIT 10
";
$statement = $pdo->prepare($sql);
if (!$statement) {
//error handling here
}
$result = $statement->execute();
if (!$result) {
//error handling here
$array = array();
while (list($id) = $statement->fetch(PDO::FETCH_NUM)) {
$array[] = $id;
}
$statement = NULL;
} catch (PDOException $e) {
//error handling here
}
This should leave an enumerated array of the ID's

Categories