I have a set of PHP functions for a URL shortener. I'd like to add another function which concerns updating a whole column in a MySQL table. So far I found the query which is: UPDATE urls SET redirect = 'http://example.com'
I'd like to have a text input where once I type a new URL and click "UPDATE ALL", the whole column in the database changes without having to do it from the database using the query I mentioned above. The only thing that stops me from doing so is the function(BOTTOM).
Here are the functions I mentioned earlier:
function createLink($slug,$url,$title,$disc,$thumb,$redirect){
global $nsqlQuery;
$f = array('slug','url','title','disc','thumb','redirect','time');
$v = array($slug,$url,$title,$disc,$thumb,$redirect,time());
$row = array_combine($f,$v);
$result = $nsqlQuery->insert("urls",$row);
return $result ? $result : false;
}
function getLink($by='NA',$val='NA'){
global $nsqlQuery;
if($by=='NA'):
$where = null;
else:
$f = array($by);
$v = array($val);
$where = array_combine($f,$v);
endif;
$result = $nsqlQuery->select("urls",'*',$where);
return $result ? $result : false;
}
function deleteLink($id){
global $nsqlQuery;
$f = array('id');
$v = array($id);
$where = array_combine($f,$v);
$result = $nsqlQuery->delete("urls",$where);
return $result ? $result : false;
}
Here's the public function that concerns updating the table and setting a new value to a certain column.
public function update($table,$row,$where,$where_condition=null,$dev='OFF'){
$query = "UPDATE ".$table." SET ".$this->getSetClause($row)." ".$this->getWhereClause($where,$where_condition);
if($dev=='ON')
return $query;
$response = $this->query($query);
return $response ? true : false;
}
Here's my progress so far which prompts a 500 error.
function updateRedirect($redirect){
global $nsqlQuery;
$where = $redirect;
$result = $nsqlQuery->update("urls",$where) SET ".$nsqlQuery->select("urls",'*',$where);
return $result ? $result : false;
}
The whole nsqlQuery.php file just in case.
Related
I have table -> subkategori
and I can't insert the id_kategori attribute to table portfolio
i have a code for the model :
function get_subcategories($id_kategori){
$query = $this->db->query("SELECT id_kategori from subkategori WHERE id_subkategori=".$this->input->post('a'));
return $query->result();
}
and the controller here :
if ($this->input->post('a')!=''){
$this->load->model('Model_app');
$this->model_app->get_subcatoegories('$id_kategori');
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);
$this->input->post('a') as you mentioned here I assume that you have input in the form and its name is a.
In Controller
if (!empty($this->input->post('a')))
{
$this->load->model('Model_app');
$id = $this->model_app->get_subcatoegories($this->input->post('a'));
if (empty($id)) {
$id_kategori = '';
} else {
$id_kategori = $id[0]['id_kategori'];
}
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);
In Model
function get_subcategories($id_kategori)
{
$query = $this->db->query("SELECT id_kategori FROM subkategori WHERE id_subkategori = $id_kategori");
return $query->result_array();
}
You can get last insterted if with $this->db->insert_id();
In your, if statement you didn't assign the database value to the $id_kategori variable. Hence while inserting the empty value into the table it inserts as 0(int field).
And also when you pass a variable to a function it should not be single quoted. You have to pass the post variable but you are passing a variable which is undefined.
if ($this->input->post('a')!=''){
$this->load->model('Model_app');
$category = $this->model_app->get_subcatoegories($this->input->post('a'));
$id_kategori = $category['id_kategori];
}else{
$id_kategori = '';
}
$data = array(
'id_subkategori'=>$this->db->escape_str($this->input->post('a')),
'id_kategori'=>$id_kategori
);
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
I called my update sql every time run the php file and it return true statement but record cannot update perfectly. I want to know that where my code goes wrong? Please help me and I will appreciate it. Thanks in advance.
This is my php code in event-listing.php:
$update_event_list = $event->updateeventlist($type = 1);
This is my sql statement in Event.inc.php :
function updateeventlist($type){
global $db;
$stmt = "SELECT * FROM "._CONST_TBL_EVENT." WHERE type = ".$type;
if($rs = $db->Execute($stmt)){
while($rsa = $rs->FetchRow())
{
if($rsa['start_date'] < strtotime("now")){
$updateEvent = "UPDATE "._CONST_TBL_EVENT." SET type = 2 WHERE id = ".$rsa['id'];
}
}
}
return true;
}
I have tried to echo out the statement and it return true statement that I want.
You need to add execute function after the update query.
$rs = $db->Execute($updateEvent);
Query execution missing after your update Query
function updateeventlist($type){
global $db;
$stmt = "SELECT * FROM "._CONST_TBL_EVENT." WHERE type = ".$type;
if($rs = $db->Execute($stmt)){
while($rsa = $rs->FetchRow())
{
if($rsa['start_date'] < strtotime("now")){
$updateEvent = "UPDATE "._CONST_TBL_EVENT." SET type = 2 WHERE id = ".$rsa['id'];
$db->Execute($updateEvent);
}
}
}
return true;
}
Below are some points that i observed in your code:-
You are not executing the update query. You are just making the query as string but not executing.
Even if you none of the records is updated or fetched you still get "true", because there is no condition to specify when to return false if it fails.
$stmt = "SELECT * FROM "._CONST_TBL_EVENT." WHERE type = ".$type;
if($rs = $db->Execute($stmt))
{
if( $rs has atleast one row rows )
{
while($rsa = $rs->FetchRow())
{
if($rsa['start_date'] < strtotime("now")){
$updateEvent = "UPDATE "._CONST_TBL_EVENT." SET type = 2 WHERE id = ".$rsa['id'];
$db->Execute($updateEvent); // this line was missing in you code
}
}
}
else
{
return false;
// $rsa has empty rows
}
}
else // execution of query fails for any reason
{
return false;
}
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 have a selet function where I pass two variables. The table and where.
However, whatever I put for where it always displays id = 1.
Could this be because it is recognising that id has a value and setting it to 1 or am I completely off the mark here?
The function is below:
public function select($table, $where){
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
return $this->processRowSet($result, true);
}
return $this->processRowSet($result);
}
The call to the function is:
$rowSet = $db->select('users','username = wayne');
Or is it the way I am setting username in the parameter?
username is a String then it is necessary to write
$rowSet = $db->select('users','username = "wayne"');