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.
Related
I've been looking up around for a couple tutorials of this and I've seemed out of luck. Basically, I have a database containing a winner's user ID (corresponding to the winners user ID) and a loser's ID. I am trying to create a members profile where it counts up all the rows the member has won. Here is what I have came up with:
$web = mysqli_query("select SUM(matches) WHERE WinnerUID='".$req_user_info['id']."'");
$web_sum=mysqli_fetch_assoc($web);
echo $web_sum;
Unfortunately, it doesn't display any number. Can anyone help?
I think you're looking for COUNT() not SUM(). And you didn't include a table name. Also remember that mysqli_fetch_assoc() returns the row as an array, it doesn't return the first column's value. Also, mysqli_query() requires the connection as the first argument.
$web = mysqli_query($conn, "select COUNT(*) as total FROM matches WHERE WinnerUID='".(int)$req_user_info['id']."'");
$row = mysqli_fetch_assoc($web);
echo $row['total'];
Don't concatenate variables into your SQL. Use a Prepared Statement with bound parameters. I have casted your ID as an (int) in the above code, which is a quick fix but you should switch to a Prepared Statement.
Prepared Statement example (object oriented interface instead of procedural):
if ($stmt = $conn->prepare("select COUNT(*) from matches WHERE WinnerUID = ?")) {
$stmt->bind_param("i", $req_user_info['id']);
$stmt->execute();
$stmt->bind_result($web_sum);
$stmt->fetch();
echo $web_sum;
$stmt->close();
}
How would i get the rowID for an update query (i am of course not updating by rowID)
The below code is what i am using (as a public function within a Class), but of course using "lastInsertId()" is not working for me (i didnt really expect it to work and it returns 0)
$query = "UPDATE tSecurityDepositPaymentAddresses
SET
tGuardians_GuardianID = ?
WHERE tGuardians_GuardianID = 0
LIMIT 1";
$stmt = $db->prepare($query);
$stmt->execute(array($GuardianID));
return $db->lastInsertId();
Could i combine the update query within a nested select? or is there a simpler way?
sorry if my question sounds bumb, but im still learning...
Thanks
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 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
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);