I have a table where two entries has id = 10. My SQL update query looks like this:
$q = "UPDATE `table_name` SET `col_name` = 'value' WHERE `id` = ?";
if($con-prepare($q)){
$stmt->bind_param("i","10");
$stmt->execute;
$stmt->fetch;
$stmt->close();
}
The query will not run, where is the error in it? And also, when it does run, will it update ALL entries where id = 10 or just the first one?
$stmt->execute();
$stmt->fetch();
Do not forget the () to show that's a method call else PHP interprets it as a property access.
And write: $stmt = $con->prepare() instead of $con-prepare() (or do you want to subtract the return of the function call to prepare() from $con?)
It'll update all the entries with id=10
Related
I am trying to store the id of a username which I got from $_SESSION to a variable but I can't get the SQL statement to work. The usernames are stored in a database called users and have an ID as primary key. Can someone tell me how I can correct this? Thanks
$name = $_SESSION['username']; //get username of user currently logged in
$rid = $db->exec("SELECT id FROM users WHERE username = '$name'");
From the PHP documentation on PDO::exec():
PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().
This means that you cannot use exec() on a SELECT query - instead, you must use query() or prepare(). For any queries using variables or user-input, use prepare() and placeholders in the query for variables, like below, to protect your database against SQL-injection.
$stmt = $db->prepare("SELECT id FROM users WHERE username = :name");
$stmt->execute(["name" => $name]);
if ($row = $stmt->fetch()) {
// $row holds the id
} else {
// No rows were returned at all! No matches for $name
}
Now $row holds the id(s) if the query returned any result at all. Depending on your fetch-type, it might be $row['id'], $row[0], $row->id or a combination of these.
If you expect more than one result, you need to loop while ($row = $stmt->fetch()), or use $stmt->fetchAll();
http://php.net/manual/en/pdo.exec.php
How can I prevent SQL injection in PHP?
I have this function which fetches "flightsize" out of a DB and uses it to setup an object.
I need to include a failsafe that, if there is no flightsize in the DB, makes flightsize = 6.
I read that i would want to use IFNULL for this, but unfortunally i cant get it to work.
Can someone assist me ?
In addition, would it be better to use IFNULL or create a new table entry for this "flight" to future selects will work ?
public function getFlightSize($gamedata){
$stmt = $this->connection->prepare(
"SELECT
shipid, flightsize
FROM
tac_flightsize
WHERE
gameid = ?"
);
if ($stmt){
$stmt->bind_param('i', $gamedata->id);
$stmt->bind_result($shipid, $flightsize);
$stmt->execute();
while($stmt->fetch()){
$flight = $gamedata->getShipById($shipid);
$flight->flightSize = $flightsize;
$flight->populate();
}
$stmt->close();
}
}
SELECT
shipid, IFNULL(flightsize,6) AS flightsize
FROM
tac_flightsize
WHERE
gameid = ?
Should work, however if gameid is not present in your table, you will get no records at all in return and you will have to handle the situation in your php code.
I perform the mysql query to check if any number of row effected on the user input data with the help of mysql_num_rows($query). Only one row will effect always as I made some rows are unique. If one row effect, I want to get the ID of that Row. I means the auto increment ID of the same row.
The same row contains many fields, its better if I come to know how to get the entry of other fields.
Thanks stack for your solutions.
Have you tried SELECT id FROM table WHERE value=condition? If you query that you will get the id of the row that matches your condition. Replace id with the identifactor row, table with your table name, value and condition with your conditions.
$query = "SELECT id FROM table WHERE value=condition";
$result = mysql_query($query);
if ($row = mysql_fetch_row($result)) {
//$row contains valid information.
}
Btw: donĀ“t use mysql_* anymore, its deprecated, look at PDO or mysqli_*
$query = "SELECT mysql_id
FROM table";
$stmt = $db->prepare($query);
$stmt->execute();
$id = $stmt->fetchColumn();
You'll probably have to add a "WHERE" clause to your query statement and then pass the values into in array using a prepared statement.
just use mysql_insert_id();
this function after executing the insert query.
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
$lastInsertId=mysql_insert_id();
echo $lastInsertId;
I am trying to understand this SQL statements :
$id = 5;
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
Can someone please explain me step by step what exactly is going on here?
From what i understand :
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
1) $stmt is about to take as iinput an SQL query. The SQL query is to select all the rows from a table that their id is equal to 5.
$stmt->execute(array('id' => $id));
2) We execute the statement. Now the $stmt has these rows?
$row = $stmt->fetch()
3) This is the most confusing line for me. What exactly happens here? Variable "row" takes one by one the rows that have id = 5 ? Is that what fetch() does ? And if yes , how exaxtly does it return the results? Its an array of all the correct answers? EG all the rows that have id = 5 ? I dont understand how exactly this while loop works here.The first time it runs "row" will have the first row ? The second time it runs , will have the second row that satisfies our creteria (id = 5) and so on? Is it like that every time i run fetch one result will be returned? And next time i run fetch , the next result , till there is no more result to satisfy the query?
I thing i am so close to get this one. Anything that could help me understand it completely would be highly appreciated !
I'll explain as comments:
$id = 5;
// Create a prepared statement - don't actually execute the statement yet.
// The :id value in the statement will be replaced by a parameter value (safely) when the
// statement is executed
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
// Execute the statement against the DB - the $stmt var now contains the result set for the
// executed statement. e.g. it contains *all* the results that the query fetched
$stmt->execute(array('id' => $id));
// Now we loop through the rows in the result set (they are all in memory at this point).
// "fetch" will start from row 1 and return the next result each time you call it again.
// when there are no more rows it returns FALSE and therefore breaks out of the while loop
while($row = $stmt->fetch()) {
print_r($row);
}
Just checking docs also and whilst this is how it was done previously (been years since I've touched PHP) it looks like stmt->fetch() actually places results into bound variables:
http://php.net/manual/en/mysqli-stmt.fetch.php
$row = array();
stmt_bind_assoc($stmt, $row);
// loop through all result rows
while ($stmt->fetch())
{
print_r($row);
}
Does the code you originally posted actually work? It doesn't appear you bind any variables and therefore since the $stmt-fetch() call returns bool TRUE/FALSE it would seem to be that $row would not get set to anything but TRUE/FALSE
here it uses PDO for execution,
Repeated SELECT using prepared statements through which you can call repeated query
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
it defines the prepared statement where :id is placeholder
$stmt->execute(array('id' => $id));
this places assigns the value to placeholder and execute the query
$row = $stmt->fetch()
it fetch the record from select
for more reference visit the link
http://www.php.net/manual/en/pdo.prepared-statements.php
I'm trying to count all of the rows from an item list where the id matches a user input. I am switching all of my code from mysql to PDO as I have learned it is much better.
The code below is what I found to work in my situation.
$id = '0';
$sql="SELECT count(*) FROM item_list WHERE item_id = $id";
$data=$connMembers->query($sql)->fetchcolumn();
echo $data;
However, It is not safe for a live site due to sql injections.
I want to know how can I change it to work whare it sanatizes the user input.
I would prefer using a prepare and execute functions so the variables are kept seperately.
So is there something I can do?
This is where you start binding parameters. I prefer to do it using ? and one array for inputs.
Assuming $connMembers is your PDO object:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ?";
$input=array($id); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
To add more variables to your sql, just add another ? to the query and add the variable to your input.
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ? AND item_name=?";
$input=array($id, $name); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
OR you can use bindParam:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = :itemID";
$statement=$connMembers->prepare($sql);
$statement->bindParam(':itemID', $id);
/*Here I am binding parameters instead of passing
an array parameter to the execute() */
$statement->execute();
$data=$statement->fetchObject();
var_dump($data);