This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
I'm trying to pull all the "totalsDate" values from a table "totals" and then either INSERT a new record or UPDATE an existing one based on a variable $date.
//getting all the dates from the totals table and assigning to row
$sqlDate = "SELECT totalsDate FROM totals";
$query = mysqli_query($dbCon, $sqlDate);
//$row = mysqli_fetch_array($query);
while($row = mysqli_fetch_array($query)){
$rowDate = $row['totalsDate'];
//if statement to either update the totals table or create a new record
if($rowDate = $date){
$sqlThree = "UPDATE totals SET lodgements = '$lodgementsAfter' WHERE branch_name = '$branchTest' AND totalsDate = '$date'";
$query = mysqli_query($dbCon, $sqlThree);
}
else {
$sqlFour = "INSERT INTO totals VALUES(NULL, '$branchTest', 0, '$amount', 0, '$date')";
$query = mysqli_query($dbCon, $sqlFour);
}
}
The update part works, however my else statement will never be executed and a new record cannot be entered. I also get this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
I'm a bit confused on using the mysqli_fetch_array and how to actually use the data?
Thanks for any help.
One of the problem is that $query gets overwritten inside the loop; see here:
while($row = mysqli_fetch_array($query)){
// ...
$query = mysqli_query($dbCon, $sqlThree);
// ...
}
You should either a) don't store the result of mysqli_query() at all, or b) choose a different variable name, e.g. $update_res = mysqli_query(...);.
Better yet, use a single query to do both:
INSERT INTO totals VALUES (NULL, :branch, 0, :amount, 0, :date)
ON DUPLICATE KEY UPDATE lodgements = :lodgements
Just make sure the proper unique constraints are defined on the table.
your db query is not correct. You are not getting a good result back from your query. The error is saying it expects the result to be an array and its not. its returning a true of false.
read this mysqli_query
for more help.
do you have access to the db command line? what does the query return. Are you certain your db connection info is correct?
i found it.
$rowDate = $date should be $rowDate == $date or $rowDate === $date
your sql result is an array
$row[0] = "1st result"
$row[1] = "2nd result"
..etc
so theortically if you have more then 1 result, it should be doing multiple updates/inserts. are you seeing that? if its just one result then clearly 2014-02-13, 2014-02-26 are not the same.
$sqlDate = "SELECT totalsDate FROM totals where totalsDate='" . $date . "'";
this will return results, with only records that have $date.
$rowcount=mysqli_num_rows($query);
if ($rowcount) < 1))
{
insert;
}
else
{
update;
}
Related
This question already has an answer here:
PDO fetch returns only first row
(1 answer)
Closed 2 years ago.
A table called "checks" has fields ID;email;pass;entered;firstname;lastname;trading.
The only code in this test is the DB connection and the new PDO connection made prior to these snippets. The following snippet reports correctly that there are 5 users in the table "checks".
$sql = "SELECT COUNT(*) AS num FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo '<br>' . $row['num'] . ' users exist.';
This snippet which follows immediately after the above doesn't show the expected result.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute($id);
$users = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($users);
The print_r statement results in the first array being printed correctly with all fields/contents correctly displayed.
On the next line it prints only the email field contents from each row as a single string!
I'm probably missing something obvious but I just can't spot it. Help please?
PDO::fetch() returns a single row from the result set. You need PDO::fetchAll() instead.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC); // <--- here
This question already has answers here:
Warning: mysqli_query() expects parameter 2 to be string, object given in
(2 answers)
Closed 3 years ago.
Can anyone help me with this error:
Warning: mysqli_query() expects parameter 2 to be string, object given .. on line 25.
<?php
session_start();
include('includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'
if (!mysqli_query($con,$query))
{
$query = mysqli_query($con, "SELECT * FROM combo where combo_id=1");
$row=mysqli_fetch_array($query);
$price=$row['combo_price'];
$payable=$pax*$price;
<?php
session_start();
include('includes/dbcon.php');
// you're missing some syntax here..
// also your $query IS your query so it should be $query = "SELECT * FROM ";
$query = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'
// you don't need this above line.. it does it all right here...
if (!mysqli_query($con,$query))
{
$query = mysqli_query($con, "SELECT * FROM combo where combo_id=1");
$row=mysqli_fetch_array($query);
$price=$row['combo_price'];
$payable=$pax*$price;
// missing closing brackets. }
Your code has multiple problems. Missing ;, repeated calls to mysqli_query, SQL injection and no error checking.
Instead of checking whether the query was successful with if enable exceptions at the top of your file. Use prepared statements, preferably in object-oriented way.
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // this line enables exceptions
include 'includes/dbcon.php';
$stmt = $con->prepare('SELECT * FROM reservation WHERE r_date=?'); // ? is a placeholder for binding data
$stmt->bind_param('s', $date); // bind data to SQL statement as a string(s)
$stmt->execute();
$reservations = $stmt->get_result();
// if your SELECT found some record then loop on the result set fetching each row one by one
while ($row = $reservations->fetch_assoc()) {
$combos = $con->query("SELECT * FROM combo where combo_id=1"); // if there is no data to be bound then we can use query
$row = $combos->fetch_assoc(); // fetch the matching combo row
$price = $row['combo_price'];
$payable = $pax * $price;
}
Your variable named query should only be your... query
$result = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'";
Also even if you think you will get back a record, function mysqli_fetch_array
will always return an array. So you need to select the first item in the array and then the key or index.
$price = $row[0]['combo_price'];
Some code practices. Don't put everything inside your IF. Because if it fails $payable will be undefined and throw an error. Initialize it on top of your script. Also you need to store the return value of mysqli_query as you need to free the memory used for it.
mysqli_free_result($result);
This question already has answers here:
How do I insert an array of values into different columns of a mysql table?
(3 answers)
Closed 7 years ago.
$rate=[10,20,40,50,70];
How do I insert the value in below query?
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
I tried below but it inserts same value in all column for a record and creates new record for each new value:
foreach($rate as $key->$value)
{
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$value}','{$value}', '{$value}','{$value}','{$value}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
Edited based on answer given
public function rentalRate()
{
$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
unset($rate);
}
Simply use implode and that's it
$rate = [10,20,40,50,70];
$rate = implode("','",$rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
echo $sql;
Foreach is not useful in this case, because you want to integrate more than one array element in one query and you do not have a multidimensional array. Just use your first query:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
And - if you really want to use foreach:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(";
foreach($rate as $value)
$sql .= "'$value', ";
$sql = rtrim($sql, ", ") . ")";
just simple (note implode will only work with integers, without need to quoate)
$rate=[10,20,40,50,70];
$r_sql = '';
foreach($rate as $r) {
$r_sql.="'$r',";
}
$r_sql = trim($r_sql,',');
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(".$r_sql.")";
Normally arrays are inserted into a different table and all tools are geared towards this. It is usually better not to fight the tools or it is likely to run into unforseen problems.
If we add a
table rental_day(id(int), rental_id(int,fk), rate(money))
Then for all the items in the array we just insert the item into one row in rental_day
later when we need the info back we can query for it like
select * from rental_day d inner join rental r on d.rental_id=r.id where r.id=something
and you will get all the info from rental_day and rental in one query.
I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!
starting query to display result:
$at = array();
$num=array();
$i=0;
while($rw=mysql_fetch_array($r))
{
echo $rw['c_number']
$number=$rw['c_number'];
$num[$i]=$number;
$i++;
echo $rw['total'];
$at[] = $rw['total'];
}
// the result of this query is like:
Mobile numbers bills
03455919448 34
03215350700 56
03474738923 678
03573987932 344
03187438979 1324
// now want to insert it in database
$d= 'november';
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at','$d','$num')";
mysql_error();
$result = mysql_query($sql);
}
// the insertion query at end is not working and gives me error:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0004 sec )
I think you need to replace num with num1 like
$sql = "INSERT INTO `billing details`(bill,`month/year`,c_number) VALES ('$at','$d','$num1')";
And dont use mysql_* functions due to they are depricated,instead you use mysqli_* functions or PDO statements
AND put your table name in '`' it seems like two different names and for the column name month/year also
i dont know what exactly want to insert $num or $num1 ? and check your table name ,column names
$d= 'november';
int i=0; // you are saying that $at has all bills
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at[i]','$d','$num1[mobile_number]')";
$result = mysql_query($sql);
if (mysql_error()) die('Error, insert query failed');
i++;
}