I just thought about this case and how to do it a bit more "professional". Does not seem to as if this the way to go even though I do not know any other. Somebody?!
$query = "SELECT col1 FROM ".PREFIX."table WHERE (col2 = :something)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":something", $something, PDO::PARAM_STR);
$stmt->execute();
$stmt->bindColumn(1, $col1, PDO::PARAM_STR);
/* get number of rows */
$num_rows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn();
if($num_rows == 1) {
$stmt->fetch();
$result = $col1;
} else {
while($stmt->fetch()) {
$result[] = $col1;
}
}
Related
I insert data into a table called 'roster'. The first column (id_roster) is an id using mysql auto-increment.
I run a SELECT to find the id_roster
I use this id_roster to insert it into a table 'roster_par_membre' along with other data
if ($insert_stmt = $mysqli->prepare("INSERT INTO `roster`(`nom_roster`, `description_roster`, `id_organisation`, `created_by`, `creation_date`,`modified_by`) VALUES (?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssiisi', $roster_name, $description_roster, $organisation_id, $user_id, $creation_date, $user_id);
if (!$insert_stmt->execute()) {
$reponse = 'Sorry, a database error occurred; please try later';
} else {
// if INSERT OK -> create a new line in roster_membre table
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
$level = 1;
//2. create a line with the roster_id and insert the membre as level 1
$insert_stmt = $mysqli->prepare("INSERT INTO `roster_par_membre`(`id_membre`, `id_roster`, `level`, `modified_by`) VALUES (?,?,?,?)");
$insert_stmt->bind_param('iiii', $user_id, $id_roster, $level, $user_id);
$insert_stmt->execute();
$reponse = 'success';
}
So far the code is working but it is not very nice.
Is there a way when we create a new line in a table to directly return a value (id with auto-increment) to be used in a sql query (to insert data into a second table)? or maybe to merge the two query (the two INSERT) in one statment?
short edit: it is an AJAX $response the return value (JSON)
Ok,solution:
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
Just need to replace all this part by
$id_roster = $mysqli->insert_id;
nice and easy. THANKS to albanx
these are the functions I used for query on projects that I do not want to use any framework (just php):
/**
*
* Executes query methods
* #param string $query the query string
* #param array $vals array of values
* #param bool $show show the query
* #return int/array/false
*/
function q($query, $vals=array(), $show_query=false)
{
$conn = new mysqli(...)
$offset = 0;
foreach ($vals as $v)
{
$cv = $conn->real_escape_string($v);//escape the value for avoiding sql injection
$fv = ($v===NULL) ? 'NULL':"'".$cv."'"; //if value is null then insert NULL in db
$qpos = strpos($query, '?', $offset);//replace the ? with the valeue
$query = substr($query, 0, $qpos).$fv.substr($query, $qpos+1);
$offset = $qpos+strlen($cv)+1;
}
$result = $conn->query($query);
if($show || $result===false) echo $query."<br>";
$rows = array();
if($result===true)
{
return $conn->affected_rows;
}
else if($result===false)
{
return false;
}
else
{
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
{
$rows[]=$row;
}
}
return $rows;
}
function lastid()
{
return $this->qval("SELECT LAST_INSERT_ID()");
}
Usage example:
q('INSERT INTO USER(name, email) VALUES(?,?)', array('admin','admin#admin.com'));
$id = lastid();
Is there a way to tell if there is results before the while loop using this style?
$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
while ($stmt->fetch()) {
}
I would like to do something before and after the while loop but I do not want to query twice.
To check the number of rows selected: $stmt->num_rows
So you might do:
if($stmt->num_rows > 0){
...
}
http://www.php.net/manual/en/mysqli-stmt.num-rows.php
Try
stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
$rows = $stmt->num_rows;
if ($rows) {
// your code
}
while ($stmt->fetch()) {
}
you can check with mysqli -> num_rows before while loop
$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three);
$numrows = $stmt->num_rows;
if ($numrows > 0) {
while ($stmt->fetch()) {
}
} else {
echo "No rows found";
}
This question already has an answer here:
$stmt->num_rows returning 0 even after calling store_result
(1 answer)
Closed 9 years ago.
i am just trying to learn prepared statement and i am following the PHP manual to guide me through, i have checked the answers regarding this problem on stackoverflow but, i can't find any solutions, the $stmt->num_rows always ( Return 0 )
there is a post on stackoverflow discussed the problem and they advised to use
$stmt->store_result() just before the $stmt-num_rows, but the $stmt->num_rows return 0
some one please can tell me what i am doing wrong here.... i am just sick of the procedural style coding and i want to enhance my skills with prepared statement
here is the function down below
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows();
$user = array();
for ($counter = 0; $row = $res->fetch_assoc(); $counter++)
{
$user[$counter] = $row;
}
return $user;
}
// This is the second update
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows;
$user = array();
while($row = $res->fetch_assoc())
{
$user[] = $row;
}
return $user;
}
// third update
function get_alll()
{
// ** Initializing the Connection
$mysqli = Connect();
// no need to use * character,
// need to write query this way
$sql = ( ' SELECT `id`,`fname`,`lname`,`uname`,`email` FROM `users` ' );
$stmt = $mysqli->prepare($sql);
// here need to use bind param
$stmt->bind_result( $id, $fname, $lname, $uname, $email);
$stmt->execute();
// it's important to store the result
// before using num rows
$res = $stmt->store_result();
echo $num_count = $stmt->num_rows;
//
while($stmt->fetch())
{
echo $fname;
}
}
num_rows is a property, not a method, try with $stmt->num_rows without brackets
I've been searching the internet for a while now, but since I'm new to MySQLi, I cannot solve this problem myself. This is my code so far. I want to return the result as an array.
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo)) {
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error.' in query: '.$userinfo;
} else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$parameters[$var] = &$$var;
}
return $parameters;
}
$stmt->close();
}}
Hopefully someone can help me get this code working, or help me find an alternative.
Have you looked at using fetch_array
http://php.net/manual/en/mysqli-result.fetch-array.php
Working from your code
function myFunction($u_id, $mysqli){
$userinfo = "SELECT email, name, street, placename FROM users WHERE u_id = ? LIMIT 1";
if($stmt = $mysqli->prepare($userinfo))
{
$stmt->bind_param('i', $u_id);
$stmt->execute();
if(!$stmt->execute())
{
echo $stmt->error.' in query: '.$userinfo;
}
else {
//this is what i found somewhere on the internet, and it gives me an array with the right keys but empty values.
$parameters = array();
while ($row = $stmt->fetch_assoc()) {
$parameters[] = $row;
}
$stmt->close();
return $parameters;
}
$stmt->close();
}
}
I am going through my code and I am running so many queries it is getting long. If I just want to store a single variable with a value, I have to do this:
switch($type) {
case "next":
if ($stmt = $mysqli->prepare("SELECT sort_order FROM user_slides WHERE user_id = ? AND sort_order > ? ORDER BY sort_order LIMIT 1")) {
$stmt->bind_param('is', $user_id, $sortId);
$stmt->execute();
$stmt->bind_result($next_sort_id);
$stmt->store_result();
$stmt->fetch();
return $next_sort_id;
$stmt->close();
}
break;
case "first":
if ($stmt = $mysqli->prepare("SELECT MIN(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($first_sort_id);
$stmt->store_result();
$stmt->fetch();
return $first_sort_id;
$stmt->close();
}
break;
case "last":
if ($stmt = $mysqli->prepare("SELECT MAX(sort_order) as max_slides FROM user_slides WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($last_sort_id);
$stmt->store_result();
$stmt->fetch();
return $last_sort_id;
$stmt->close();
}
break;
}
There has to be an easier way to do this. Where I can just do it like this:
$first_sort_id = QUERY HERE
$last_sort_id = QUERY HERE
So it doesn't have to be so long, it can be nice and short.
Does anyone know what I need to do to accomplish that?
First
If you use return the statement $stmt->close(); will be never executed.
Second
Get rid of two vars, you just need one. Don't get fooled by semantic meanings.
Third
A simple reorganization could be this:
switch($type)
{
case "next":
$Query = "SELECT sort_order";
break;
case "first":
$Query = "SELECT MIN(sort_order)";
break;
case "last":
$Query = "SELECT MAX(sort_order)";
break;
}
if ($stmt = $mysqli->prepare("$Query as max_slides FROM user_slides WHERE user_id = ?"))
{
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($value);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $value;
}
else
return NULL;