Checking array data in sql condition PHP - php

I would like to UPDATE the seat_status to active by checking two conditions.
1st condition = bus_id
2nd condition = seat_title
I'm using this code in function cancelbook.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
for($i=0;$i<count($seat_no);$i++)
{
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active' WHERE bus_id=:bus_id AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat_no[$i]);
}
if ($stmtactive->execute()) {
exit();
return true;
}
return false;
}
im getting this error
Notice: Array to string conversion

The way you did the loop will only update one row, to update every row you should execute your statement for each iteration.
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
foreach($seat_no as $seat) {
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title=:seat_title");
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',$seat['seat_no']);
$stmtactive->execute();
}
}

it seems $seat_no[$i] is not string and it's an array , (I suggest var_dump($seat_no[$i]); it before), my quess is it should be something the following snippet:
use
$stmtactive->bindParam('seat_title',$seat_no[$i]['seat_no']);
instead of
$stmtactive->bindParam('seat_title',$seat_no[$i]);
in your code will resolved your problem.
of course, it's better instead of using for learn to use foreach
But another solution with better performance is using just one update instead of serveral updates!!!
function cancelbook($conn,$id,$busid)
{
$stmtgetseats = $conn->prepare("SELECT seat_no from tbl_seats
WHERE bus_id=:bus_id");
$stmtgetseats->bindParam(':bus_id',$busid);
$stmtgetseats->execute();
$seat_no=$stmtgetseats->fetchAll();
$seat_numbers = array_values($seat_no);
$stmtactive = $conn->prepare("UPDATE tbl_busseats SET seat_status='active'
WHERE bus_id=:bus_id
AND seat_title IN (:seat_title"));
$stmtactive->bindParam('bus_id',$busid);
$stmtactive->bindParam('seat_title',implode(",",$seat_numbers));
$stmtactive->execute();
}
Also, remove Exit in your code, it's a bad mistake in your code

Related

SQL UPDATE value as null or string

I searched almost whole internet, but could not find something similar, yet my question looks so simple.
I have a php code like so:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = null;
}
... which simply checks if submitted value is empty or not, if it is empty, then variable $port1 = null;
then, further in the code, I need to insert this value/update it in the database
$sql_update = ("UPDATE names_10 SET `digName1`=$port1 WHERE `device_id`='$id'");
...which should set the "digname1" to null. but it won't!
I tried every combination, every type of quotes, but every time I got UPDATE error..
any ideas?
Try this:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = "NULL";
}
$sql_update = ("UPDATE names_10 SET `digName1`= $port1 WHERE `device_id`='$id'");
I would rather suggest you to use PDO when you plan to bind something like this. There are a lot of benefits using PDO that would amaze you!

Information regarding SQL queries, stored with php

So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more

Basic mysqli select

I have a select statement where I want to get all rows from a table but seem to be having a mental blockage - this should be elementary stuff but can't seem to get it working.
There are only two rows in the table 'postage_price' - and two columns : price | ref
Select statement is as follows:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row;
}
I am then trying to echo the results out:
echo $post1['0'];
echo $post1['1'];
this is not showing anything. My headache doesn't help either.
while($post_row = mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[] = $post_row['price'];
}
As you see: $post_row in this line: = mysqli_fetch_array($dbc, $get_postage_result) is an array. You are trying to save the whole array value to another array in a block. :)
EDIT
while($post_row = mysqli_fetch_array($get_postage_result))
...
You have $post1[]=$post_row; and $post_row is itself an array. So you can access post data with following: $post1[NUMBER][0] where NUMBER is a $post1 array index and [0] is 0-index of $post_row returned by mysqli_fetch_array.
Probably you wanted to use $post1[]=$post_row[0]; in your code to avoid having array of arrays.
You are passing 1 and 0 as string indexes, this would only work if you had a column called 0 or 1 in you database. You need to pass them as numeric indexes.
Try:
print_r($post1[0]);
print_r($post1[1]);
or
print_r($post['price']);
print_r($post['ref']);
with all your help I have found the error - it is in the mysqli_fetch_array where I had the $dbc which is not required.
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($get_postage_result))
{
$post1[]=$post_row['price'];
}
instead of:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row['price'];
}
Bad day for me :(
Thanks all
If something does not work in a PHP script, first thing you can do is to gain more knowledge. You have written that
echo $post1['0'];
echo $post1['1'];
Is showing nothing. That could only be the case if those values are NULL, FALSE or an empty string.
So next step would be to either look into $post1 first
var_dump($post1);
by dumping the variable.
The other step is that you enable error display and reporting to the highest level on top of your script so you get into the know where potential issues are:
ini_set('display_errors', 1); error_reporting(~0);
Also you could use PHP 5.4 (the first part works with the old current PHP 5.3 as well, the foreach does not but you could make query() return something that does) and simplify your script a little, like so:
class MyDB extends mysqli
{
private $throwOnError = true; # That is the die() style you do.
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result && $this->throwOnError) {
throw new RuntimeException(sprintf('Query "%s" failed: (#%d) %s', $query, $this->errno, $this->error));
}
return $result;
}
}
$connection = new MyDB('localhost', 'testuser', 'test', 'test');
$query = 'SELECT `option` FROM config';
$result = $connection->query($query);
foreach ($result as $row) {
var_dump($row);
}

Is using mysql_num_rows (rowCount in PDO) necessary in update or insert query?

Should I be using mysql_num_rows (rowCount in PDO) in update or insert query?
Currently, my code looks likes this,
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$message = "Updated successfully";
return $message;
}else{
return false;
}
}
Should I change it to like this?
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
$r = $db->query($q);
if($r){
$num = $r->rowCount();
if($num == 1){
$message = "Updated successfully";
return $message;
}else{
$message = "An error occurred";
return $message;
}
}else{
return false;
}
}
Normally, query goes through without any error, so I shouldn't worry about it too much, but which one would be a better coding practice? Or do you suggest something else?
Thanks so much in advance!
Actually the two codes do something different.
The first one will print "Update success" if the query was successfully executed. But a query can be successfully executed also without affecting any row, i.e. you have a WHERE statamenet that does not match. The second code will not print "Update success" if no rows were affected.
Of course, if you're sure that your WHERE statement has to match, you can use both codes without any difference and using the second one could help you to spot any potential bug, i.e. it doesn't match and so something went wrong (probably the id was different from the one you expected).
Generally, to answer your question, mysql_num_rows is needed only if you want to know how many lines were affected. It's not mandatory at all to use it.
So, it depends on what you want. Both are good, but they are different.
If you are 100% sure the variables are created by you and not someone else you can do it like that, but you can minimize the code more:
public function update_username(){
$q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id'";
if($db->query($q)){
return "Updated successfully";
}
return false;
}
First, because a query is executed successfully, doesn't necessarily mean that anything has been updated. So if you need to distinct the difference between a queries validity or the update change, then yes, rowCount would be a good practice.
Second, a prepared statement would be more wise to use when assigning variables (SQL injection, etc).
public function update_username(){
$q = "UPDATE usertable SET username = :user_name WHERE id = :user_id LIMIT 1";
$r = $db->prepare($q);
$r->bindValue(':user_name', $user_name);
$r->bindValue(':user_id', $user_id);
if($r->execute()){
$message = "Updated successfully: updated ".$r->rowCount();
return $message;
}else{
return false;
}
}
To avoid code duplication, maybe you should consider avoiding writing the same execution code for a query, and move that to a method/function which does that all for you, e.g
public function validateStmt($r) {
// validate query
if($r->execute()) {
// check result set
if($r->rowCount() > 0) {
return $r;
}
else {
// if a result set IS expected, then you might consider to handle this as
// a warning or an error
}
}
else {
// query invalid
}
}
Depending on the situation, you will have to choose which part you should use. mysql_num_rows() is used to check how many rows have been affected from your query you have executed. So, it's up to you to decide whether it is really necessary to add the mysql_num_rows() function in to your code or not.

issue with my update-query

I'm trying to submit an update function, but for some reason it's not working and I can't figure out why... Someone who does?
UPDATE SQL-SYNTAX:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
PHP:
$project = new Project();
$project->name = $_POST['newproject_name'];
$project->photo1 = $_FILES['images']['name'][0];
if($project->updateProject($_DB, $projectname)) {
$feedback = "OK!";
} else {
$feedback = "NOT OK!!";
}
And in case you were wondering, $project->name and $project->photo1 are filled in correctly.
Any ideas? I hope I gave you everything you need, if not, let me know!
EDIT 1: I used the 2 first answers, but no results. Yet...
EDIT 2: I also don't get anything from $feedback
It looks like you have a stray opening parenthesis after the SET keyword. Remove it.
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
public function updateProject($db, $id)
requires 2 parameters being passed but when you do
if($project->updateProject($_DB))
you're only passing 1??
Your updateProject needs two variables and the second one is missing in your call, resulting in an invalid query.
Edit: Based on your edit; I'm guessing $id needs to be an integer or a string, you are passing an object.
Exactly what row do you want to update? I don't see anything in your php code that defines the ID of the row you want to modify, you are just generating a new object, not getting one from a database for example.

Categories