PHP, phpmyadmin, mysql - php

i am having issue with inner join. in phpmyadmin i have 3 tables:
1 - proyects
2 - users
3 - proyects-users (relation table)
i am sending to php an idproyects i want to list all available users on that proyect So...
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbuser, $dbpassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM users u INNER JOIN proyects-users pu on pu.id = u.id WHERE pu.idproyect='$justavariable'");
$stmt->execute();
$result = $stmt->fetchAll();
}

You should be using parameters as indicated by other comments - but also you should avoid using '-' in any names in the database. So proyects-users would usually be proyects_users.
You could put quotes `proyects-users` around the name, but it's just not standard or convention to use '-' in any names.
You should also be checking that anything you do actually works, as any execute could fail for all sorts of reasons, so usualy
if ($stmt->execute()) {
$result = $stmt->fetchAll()
}

Related

need to SELECT and show all entries written by specific user and count it

I need to SELECT and show all entries written by specific user and number of his/her total entries
<?php include 'helperl.php'; include 'dbconn.php';
$name=$_GET['id'];
$sql="SELECT * FROM entries WHERE writer_user LIKE '%$name%'";
$result=$conn->query($sql);
$num_entry= count($result);
echo "$num_entry";
?>
First the LIKE option that you did will get you all the name that contain $user
Your query should be like
SELECT nb
FROM (SELECT writer_user,count(*) as nb
FROM entries
WHERE writer_user=you_var
Group BY writer_user)
For getting all the entries of specific user
SELECT *
FROM entries
WHERE writer_user=you_var
u can do a join in one query to get the information you wanted but there will be a duplication in the count attribut.
exemple :
entrie count
entrie1 4
entrie2 4
entrie3 4
entrie4 4
hope i helped you.
you should use SQL COUNT function to do this (SQL COUNT function
)
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Your code can look like this
<?php
try {
$name = htmlentities(strip_tags($_GET['id']));
$sql = "SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%$name%'";
// create pdf instance
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%name%'");
$stmt->bindParam('name', $name);
$stmt->execute();
$result = $conn->query($stmt)->fetchAll();
var_dump($result);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
?>

Display only the first 3 matching rows from a query via php PDO

this is for a homework assigment. I am suppose to: Demonstrate use of the SQL LIMIT clause by displaying only the first 3 matching rows from a query.
the "first 3 matching rows" part is throwing me off a bit. How do I match rows, or should I say find 3 matching rows. I know that in my table none of my rows 'match', its a simple table with 6 columns and 4 rows, I could add matching rows for demonstrating it.
I would be doing this using the PDO method via php obviously while using the sql limit statment to make it only 3 rows.
I figure a basis of the code would look something like this with a different sql statement.
php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "****select * from teams where 3 rows match****";
// use exec() because no results are returned
$stmt = $conn->prepare($sql);
$stmt->execute()
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
Just use SQL LIMIT
$sql = "select * from teams LIMIT 3";
$sql = "select * from teams [where condition(optional)] LIMIT 0,3";
where 0 means first row and 3 is number of rows you want
Refer http://www.w3schools.com/php/php_mysql_select_limit.asp

PDO exception on correct MySql query

I'm trying to update a MySql database using PDO in PHP.
I need to launch 4 lines of SQL code. The last one is the SELECT statement, which should return only one integer value.
The error thrown is:
exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in C:\xampp\htdocs\php\set-lesson-finished.php:22
Stack trace:
#0 C:\xampp\htdocs\php\set-lesson-finished.php(22): PDOStatement->fetchColumn()
#1 {main}
And here is the code:
try {
$db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$query_save = $db_connection->prepare('
DELETE FROM unfinished_lessons WHERE bought_id = :bought_id;
INSERT INTO finished_lessons VALUES (:bought_id, :time_invested, NOW());
UPDATE users SET points = points + :points_earned WHERE id = :user_id;
SELECT points FROM users WHERE id = :user_id;
');
$query_save->bindValue(':user_id', (int)$_SESSION['user_id'], PDO::PARAM_INT);
$query_save->bindValue(':bought_id', (int)$_POST['bought_id'], PDO::PARAM_INT);
$query_save->bindValue(':time_invested', (int)$_POST['time_invested'], PDO::PARAM_INT);
$query_save->bindValue(':points_earned', (int)$_POST['points_earned'], PDO::PARAM_INT);
$query_save->execute();
echo $query_save->fetchColumn();
} catch (PDOException $e) {
echo $e;
}
This is not a single query but four queries together. You'll get four different result sets which need to be retrieved independently.
The error you're seeing is occurring because you can't call fetchColumn() on a DELETE query (it doesn't return a result set). Likewise for INSERT and UPDATE.
You could experiment with PDOStatement::nextRowSet(), but it's probably easier to run the four queries separately. If you're concerned about having an all-or-nothing update you should use a transaction with PDO::beginTransaction() and PDO::commit()
When queries gets complex you need to use a stored procedure:
DELIMITER //
CREATE PROCEDURE your_sp(IN `p_bought_id`, IN `p_time_invested`, IN `p_points_earned`, IN `p_user_id`)
BEGIN
DELETE FROM unfinished_lessons WHERE bought_id = p_bought_id;
INSERT INTO finished_lessons VALUES (p_bought_id, p_time_invested, NOW());
UPDATE users SET points = points + p_points_earned WHERE id = p_user_id;
SELECT points FROM users WHERE id = p_user_id;
END //
DELIMITER ;
You call it in one query like this:
$query_save = $db_connection->prepare('
call your_sp(:bought_id, :time_invested,:points_earned, :user_id)
');
You should use mysqli extension (and not PDO) if you absolutely want to run multiple statements at the same time.
As you can see in this Feature comparison (see the comparison table), only ext/mysqli has full support for multiple MySQL queries (and also supports all MySQL 5.1+ functionnality).
And, as Drupal's dawehner says, MySQL PDO no longer allows multiple database queries to be executed at the same time.
I've split the queries in four and everything works as expected:
$db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db_connection->beginTransaction();
$query = $db_connection->prepare('DELETE FROM planz_unfinished_lessons WHERE bought_id = :bought_id;');
$query->bindValue(':bought_id', (int)$_POST['bought_id'], PDO::PARAM_INT);
$query->execute();
$query = $db_connection->prepare('INSERT INTO planz_finished_lessons VALUES (:bought_id, :time_invested, NOW())');
$query->bindValue(':bought_id', (int)$_POST['bought_id'], PDO::PARAM_INT);
$query->bindValue(':time_invested', (int)$_POST['time_invested'], PDO::PARAM_INT);
$query->execute();
$query = $db_connection->prepare('UPDATE planz_users SET points = points + :points_earned WHERE id = :user_id');
$query->bindValue(':points_earned', (int)$_POST['points_earned'], PDO::PARAM_INT);
$query->bindValue(':user_id', (int)$_SESSION['user_id'], PDO::PARAM_INT);
$query->execute();
$query_check = $db_connection->prepare('SELECT points FROM planz_users WHERE id = :user_id');
$query_check->bindValue(':user_id', (int)$_SESSION['user_id'], PDO::PARAM_INT);
$query_check->execute();
$db_connection->commit();
$_SESSION['points'] = $query_check->fetchColumn();
echo $_SESSION['points'];
Note the use of beginTransaction and commit, as they should speed up the querying.

Player score update with PHP MySQL

I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work

How to make prepared statement using PDO in advanced queries?

I would like to ask for help with converting my mysql_* query to prepared statement using PDO technology. There are many of them which I cannot find on the internet how to solve them properly - mostly advanced ones like this one for example:
mysql_query("SELECT * FROM pet_auction JOIN people ON (pet_auction.pet=people.guid)
LEFT OUTER JOIN login.account ON (pet_auction.winner=login.account.id)
WHERE active=1 AND seller=$userid ORDER BY id DESC");
How to succesfully convert it to PDO STMT using these?:
$people = new PDO("mysql:host=localhost;dbname=people", "myuser", "mypass");
$login = new PDO("mysql:host=localhost;dbname=login", "myuser", "mypass");
Thank you all I rather will not try else it would be false because i tested already ... I have no idea how to convert LEFT OUTER JOIN and multiple databases together.
You do not need to open a pdo object for each database. Just give myuser grant access to both login and people databases. Then query like so:
$dbh = new PDO("mysql:host=localhost;dbname=people", "myuser", "mypass");
$stmt= $dbh->prepare("SELECT * FROM pet_auction JOIN people ON (pet_auction.pet=people.guid)
LEFT OUTER JOIN login.account ON (pet_auction.winner=login.account.id)
WHERE active=1 AND seller=:userid ORDER BY id DESC");
$stmt-> execute(array(':userid' => $userid));
$variable = $stmt->fetch(PDO::FETCH_ASSOC);
$dbh = new PDO($dsn, "myuser", "mypass");
$select = $dbh->prepare("SELECT * FROM `table`");
$select -> execute();
$variable = $select->fetch(PDO::FETCH_ASSOC);
where $dsn is a string containing 'mysql:dbname=racerost_reekris_db;host=localhost'
the query can contain any mySQL query including joins.

Categories