I am trying to get the insert id from a newly inserted row. I use the following method to query. However I am unable to get the inserted id.
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
$id = $result->insert_id; //no result, what do I put here?
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows, 'id'=>$id);
} else {
//error
return array('error'=>'Database error');
}
}
How can I modify this method to get the insert id?
$id = mysqli_insert_id($link);
This value would be called the "identity", keep that in mind when searching for information pertaining to this.
check the below links
mysql_insert_id()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html
Related
These lines are from a php function on a web server, the client is an ios app,
I get an error on the result2 query
$result = query("SELECT field1 FROM table1 WHERE field2='%s' limit 1", $value);
$row = mysql_fetch_array($result);
$result2 = query("SELECT field2 FROM table1 WHERE field3='%s' limit 1", $row['field1']);
on Xcode I get the error (in json):
{
error = "The operation couldn't be completed. (Cocoa error 3840.)";
}
here is the definition of the function query
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
what's wrong with that query?
thanks
You are using mysqli_ functions in your query() function yet you are trying to use mysql_fetch_array() to get the results. You need to use: mysqli_fetch_array()
http://www.php.net/manual/en/mysqli-result.fetch-array.php
Actually it looks like your query() function does it for you. You shouldn't need to use a function at all. Look at this section of your query() function:
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
However not sure why it says it is json cause it is just a normal array not a json array. So you should just use this in your code:
$row = $result['result'][0];
This will get the first row.
maybe you have to json_encode the result?
//return json
return json_encode(array('result'=>$rows));
I have a function query:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
The function works just fine when I use it like this:
$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);
However I am getting no result when $g is a value retrieved from a method. For example lets say I have a method getMonth() from a class Date that returns the current month of May as 05% when echoed. I try the code below and get nothing from the database:
$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
I am pretty sure that I am making a simple mistake, but I can't seem to figure it out. How can I fix this? Any help would be greatly appreciated.
Do something that your method return only 05 part from 05%. and append % after that for example
$h = $time->getMonth();
$h = "$h%";
and then it should work
I am using the following method to query from my SQL database:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = (what goes here?)
I am trying to get the string name from users, how can I do this?
If your query is right then
try this:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = $result['result'][0]['name'];
You forgot to pass the value to the function
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1")
$name = "";
if(! isset($result["error"]) and isset($result["name"])) // check it returns error or not. then check name field exist or not.
{
$name = $result["name"];
}
echo $name;
I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.
Here is my code:
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
} else {
return $data = $query;
}
Before this code, if the code that query from database:
//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
$query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}
I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.
The script below:
//create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
$r1 = $row->rowone;
$r2 = $row->rowtwo;
$r3 = $row->rowthree;
$englishdate = $row->dob_eng;
$chinesedate = $row->dob_chi;
//add all initial data into the matrix variable for easier access to them later
$rows[0]
$rows = array(
array($r1),
array($r2),
array($r3),
array()
);
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
return ($a % $m) + 1;
}
//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
//function to access the global variable.
global $rows;
$row = $rows[$rowId];
while (sizeof($row) < $populationCount) {
$rowInd = sizeof($row) - 1;
$m = incmod($row[$rowInd], $mod);
array_push($row, $m);
}
//set the row back into the global variable.
$rows[$rowId] = $row;
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
}
I am using same query again and again on different pages in between to fetch result. I want to make a function for this query.
$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
echo $row ['name'];
How to make and how to call the function?
sample class stored sample.php
class sample
{
function getName(id)
{
$result = mysql_query("SELECT name FROM tablename where id='$id'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
}
use page include sample.php,then create object,then call getName() function.
<?php
include "db.class.php";
include "sample.php";
$ob=new sample(); //create object for smaple class
$id=12;
$name=$ob->getName($id); //call function..
?>
This is a good idea but first of all you have to create a function to run queries (as you have to run various queries way more often than a particular one)
function dbget() {
/*
easy to use yet SAFE way of handling mysql queries.
usage: dbget($mode, $query, $param1, $param2,...);
$mode - "dimension" of result:
0 - resource
1 - scalar
2 - row
3 - array of rows
every variable in the query have to be substituted with a placeholder
while the avtual variable have to be listed in the function params
in the same order as placeholders have in the query.
use %d placeholder for the integer values and %s for anything else
*/
$args = func_get_args();
if (count($args) < 2) {
trigger_error("dbget: too few arguments");
return false;
}
$mode = array_shift($args);
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if ($mode === 0) return $res;
if ($mode === 1) {
if ($row = mysql_fetch_row($res)) return $row[0];
else return NULL;
}
$a = array();
if ($mode === 2) {
if ($row = mysql_fetch_assoc($res)) return $row;
}
if ($mode === 3) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
then you may create this particular function you are asking for
function get_name_by_id($id){
return dbget("SELECT name FROM tablename where id=%d",$id);
}
You should probably parse the database connection as well
$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function get_row_by_id($id, $database_link){
$result = mysql_query("SELECT name FROM tablename where id= '{$id}");
return mysql_fetch_array($result);
}
Usage
$row = get_row_by_id(5, $database_connection);
[EDIT]
Also it would probably help to wrap the function in a class.
function getName($id){
$result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
call the function by
$id = 1; //id number
$name = getName($id);
echo $name; //display name