Is it possible to use bind_result and bind all of the columns into an array? The reason I ask is because I execute the code on lots of different tables and don't want to have to put each column in when the amount changes.
$stmt = $mysqli->prepare("SELECT * FROM " . $company . " WHERE `id` = ?");
$stmt->bind_param('s', $route);
$route = $_GET['routeid'];
$stmt->execute();
$stmt->bind_result($test);
Currently that's what my PHP looks like. Clearly it's wrong because you must bind them to something, I just need to know how to put the data into an array and bind it to that (hoping you can understand that poor explanation).
Thanks
PS. I've looked at the related answer and it only confused me. If someone could explain in a little more detail I'd appreciate it.
Why do you specifically want to use bind_result to do this when a more natural alternative already exists?
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
If fetch_assoc is not exactly what you want, other variations include fetch_row (numeric indexing) and fetch_object.
$stmt->bind_result($test['col1'], $test['col2']);
Continue adding $test['colX'] for however many columns you have.
Related
I have this PDO
$stmt = $db->prepare('SELECT * FROM channels WHERE id=:id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$result = $stmt->execute();
What now is the simplest method to access the row returned using $row['column_name']?
I know that for sure the query will only ever return a single row as it's impossible to have more than 1 row with the same id so I am looking to keep the code as simple as possible to access that row.
Examples I've seen online are quite long and complex, using while loops to loop through rows etc. that I don't need.
It should be as simple as
$row = $stmt->fetch(PDO::FETCH_ASSOC);
The examples you've seen probably have something more like
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ...
because they're designed to process a query result with multiple rows. But if you know you'll only ever have one row, you can just forgo the loop. Of course, this is assuming your query actually executed successfully and returned a result. It would be a good idea to at least check
if ($row) { ...
before you try to use it in your subsequent code.
I've recently gotten over my bad habit of using the deprecated mysql functions in favor of mysqli, and I'm having some issues.
Right now, I'm using something similar to the following:
$query = $conn->prepare("SELECT * FROM table WHERE cid = ?");
$query->bind_param('i', $id);
$query->execute();
And this is where I get stuck. In order to loop through the result, I use:
while ($row = $query->get_result()->fetch_assoc()) {
//My code here
}
However, I need to determine the number of rows returned from the query before going through the results. To do this, I need to do the following:
$query->store_result();
$rows = $query->num_rows;
But I get errors when calling both get_result and store_result on the same query.. is there an easier way to do this? Am I overthinking things? I basically just want to determine if the result set has greater than x # of rows, and if so, loop through the results.
Thanks for any help.
I asked a question earlier on today regards to Running multiple queries in loop, and building multidimensional array This code that I wrote works, but it just doesn't feel right.
The main issue I was noticing is that to do what I needed to do involved nesting queries inside the loop over of the results of a previous query. This seemed to kick up a stink of errors once I did this more than once, and after a little google time it seems that this just isn't possible to do. So I broke the queries apart and used a for loop for the second query. But this just feels messy, I'm now running two loops and I'm sure there must be a better way of doing this. Some code:
// get all to be done by each user
$stmt = $conn->prepare("SELECT activityId FROM done WHERE userId=? ORDER BY number DESC");
$stmt->bind_param("s", $idq);
$stmt->execute();
$stmt->bind_result($aiddo);
$stmt->store_result();
$num_do = $stmt->num_rows;
while($stmt->fetch()) {
$activityId_do[] = $aiddo;
}
// get location information
for($i=0; $i<=$num_do; $i++) {
$act_done = $conn->prepare("SELECT fullAddress FROM `activity` WHERE (id=?)");
$act_done->bind_param("s",$activityId_do[$i]);
$act_done->execute();
$act_done->bind_result($fullAddress);
while($act_done->fetch()) {
$do_array[] = array(
"fullAddress"=>$fullAddress,
"type"=>"do"
);
}
}
So this code above is inside a while loop over the results on a query that gets all the users a user is following.
I was wondering if there is a better way of doing this, is it possible to use some kind of sql magic on it and do it all in the query?
I just recently started using PDO, not that much experience with it, but I recently crashed into an annoying problem.
I am trying to use bindValue with a fetch statement to retrieve informatie from a database. The variables I get are from a GET, from a previous page. Everything is going wel except for the fact that it is not assigning, I guess, a right value to one of the bindValue.
PDO:
$stmt = $dbconnect->prepare('SELECT * FROM :table WHERE id=:id');
$stmt->bindValue(':table', $table);
$stmt->bindValue(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
I know the difference between bindValue and bindParam. The code is working fine when I hardcode the table value. I have been banging my head against a wall for a short hour now but I can't seem to figure it out. Could anyone beside giving me the correct syntax please explain what went wrong with my thinking because at this point I cannot think of a reason, besides maybe the misinterpretation of the string value, why this is going wrong.
Also for in the future I would like to know the precise content of the SQL command. I tried doing this:
$SQL = 'SELECT * FROM :table WHERE id=:id';
$stmt = $dbconnect->prepare($SQL);
$stmt->bindValue(':table', $table);
$stmt->bindValue(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
But this won't bind the variable values to the SQL variable. Your help is much appreciated!
EDIT:
I noticed my post is a duplicate from a FAQ post: FAQ. So my question has been answered however my insight in PDO is not enough to undertand it. Could anyone please explain what happens with the next line of code and why this works, opbtained from the posted link!
$field = "`".str_replace("`","``",$field)."`";
$sql = "SELECT * FROM t ORDER BY $field";
Answer
Thanks to silkfire I came up with fix. Before inserting the SQL string just add the string content into the SQL string:
$SQL = 'SELECT * FROM '.$table.' WHERE id=:id';
PDO does not allow table names or column names to be placeholders. Just create the query with concatenation instead, but make sure the user supplies only valid values. This should be safe.
I'm new to PHP. I have a select statement that returns 100 values for a particular record. I'd like to store these 100 values in an array. Is this the right command to store values that I get from a select statement into an array?
$result = mysql_query("select * from processed1 where record = ('$id') ");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row; //IS THIS CORRECT?
}
Is there a way where I can avoid typing in the 100 attributes for my table? example : $row[1] ... $row[100]
If you are going to learn PHP in 2011, let's do it right.
First off, mysql_query or mysql_ anything code is deprecated. Don't use it anymore.
Don't worry - what I am suggesting works great with mysql databases, but it will also work great with any database:
PDO is what the PHP community continues to add features to, so I would use that.
PDO is also way more powerful, and makes it easier to switch databases later.
MYSQLi (the i stands for improved) replaces deprecated mysql_ based queries, but I would definitely go straight to using PDO.
You could also easily create an array
of objects later with one line change!
Secondly, Phil mentioned fetchAll(). This is the end goal. The other ways simply move thru it one row at a time. This uses a bulldozer instead of a shovel. Note: not the best way of selecting really large amounts of data, as it will use up memory. Otherwise, it is fine.
To get there, use prepared procedures to protect your code from SQL injection attacks.
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
/* Fetch all of the rows into an array */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
Your code looks fine to me. But I would suggest to use mysql_fetch_assoc() instead of mysql_fetch_array(), so that keys are mapped to their values. Also, use mysql_real_escape_string() to prevent SQL injection.
$query = "Select * from processed1 where record = '".mysql_real_escape_string($id)."'";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
If you're trying to store all the database rows into an array, yes, that code should do it. A few comments, though:
As curiou57 suggested, use mysql_fetch_assoc() to be able to refer to columns in an individual row by their names. (ex: foreach ($data as $row) { echo $row['columnname']; })
Make sure you run $id through mysql_real_escape_string() if you have to continue using the mysql extension. This prevents SQL injection attacks.
If you don't have to continue using the mysql extension, consider using PDO or mysqli.
Switch to mysql_fetch_row() if you want to reference each column by a numeric index (note, zero-based). Otherwise, that looks correct.
If you decide to switch to PDO, you can use the handy PDOStatement::fetchAll() method, using the PDO::FETCH_NUM fetch style to fetch all rows as numeric arrays into an array.
This is the correct way:
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row