im trying to figure out what's wrong with this code.
im getting the Call to a member function fetch_assoc() error but I can't figure out why
for the record - im trying to build an eCommerce site for a project in college and with the following code im trying to reduce the item stock when a purchase is made.
Just to mention - I executed the SELECT query in PhpMyAdmin and it worked
<?php
require 'config.php';
session_start();
$sql = "SELECT * FROM cart,product WHERE product.product_code = cart.cart_product_code";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$stock=$row['product_stock']-$row['quantity'];
$id_stock=$row['cart_product_code'];
$sql= "UPDATE product SET product_stock='$stock' WHERE product_code='$id_stock'";
$result = mysqli_query($conn, $sql);
$query="TRUNCATE TABLE Cart";
$clear= mysqli_query($conn, $query) or die("Invalid query");
}
}
You are overriding the $result object inside the while loop by querying an update query. You could execute the query without setting any variable :
$sql= "UPDATE product SET product_stock='$stock' WHERE product_code='$id_stock'";
mysqli_query($conn, $sql);
Also, I strongly suggest you to use prepared statement to avoid any form of SQL injection.
Related
I am trying to output a count of the number of results I have in a survey. The query itself ($sql) seems correct, because I do not get the error I have included, when I know that works. What isn't happening is the output. I have all my PHP tags and my database connection in place just fine, so I haven't included them here. They function just fine. What I need to know is how to get this outputted. This echoing for a count had worked for a previous PHP database set, but it is not working for this one.
My database has just ONE table, named survey. 'sur_cnt' is an auto-increment field that adds up whenever a new input is added to the database. My page output comes out blank, so I believe something is wrong with the echo, but I'm not sure what.
$sql = "SELECT COUNT(`sur_cnt`) FROM Survey";
$num = mysqli_query($db, $sql) or die('Error
querying database.');
$num_results = $result->num_rows ;
echo $num_results ;
try this query
because COUNT() using with groub by cluase
$sql = "SELECT * FROM Survey"; //remove count()
$result= mysqli_query($db, $sql) or die('Error querying database.');
$num_results = mysqli_num_rows($result) ;
echo $num_results ;
You need to use some form of fetch method to actually retrieve the count from your SQL statement - just the same as any other type of data from the database...
$sql = "SELECT COUNT(`sur_cnt`) FROM Survey";
$num = mysqli_query($db, $sql) or die('Error querying database.');
$row = mysqli_fetch_array($num) ;
echo $row[0] ;
The majority of this code works just fine, the database get updated when I click on the button, but the last query (the UPDATE one) doesn't execute for some reason.
I tried turning on mysql log on phpmyadmin, but even there it's not executed.
It doesn't show me any error, and I really don't know what could be wrong.
$query = "SELECT username, coins FROM users WHERE userid='$userid' LIMIT 1";
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
$_SESSION['username'] = $user['username'];
$_SESSION['coins'] = $user['coins'];
$op = $user['username'];
$op = mysqli_real_escape_string($forumdb, $op);
$postcontent = $_POST['postcontent'];
$postcontent = mysqli_real_escape_string($forumdb, $postcontent);
$posttitle = $_POST['posttitle'];
$posttitle = mysqli_real_escape_string($forumdb, $posttitle);
$sectionid = $_GET['sectionid'];
$sectionid = mysqli_real_escape_string($forumdb, $sectionid);
$query = "INSERT INTO topic (section_id, name, replies, op, lastpost, lastuserid, views, sticked) values('$sectionid', '$posttitle', '0','$op', CURRENT_TIMESTAMP(),'$userid', '0', '0')";
$result = mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
$last_id = mysqli_insert_id($forumdb);
$query = "INSERT INTO posts (topic_id, content, user_id) values('$last_id', '$postcontent', '$userid')";
mysqli_query($forumdb, $query);
$query = "UPDATE section SET lastpost='$username', threads=threads+1, posts=posts+1 WHERE id='$sectionid'";
mysqli_query($forumdb, $query) or trigger_error("Query Failed! SQL: $query - Error: ".mysqli_error($forumdb), E_USER_ERROR);
You can use the following to solve your problem:
"UPDATE `section` SET `lastpost`='$username', `threads`=threads+1, `posts`=posts+1 WHERE `id`='$sectioni
It would have been helpful if you explained what "doesn't execute for some reason" means.
Either you get an error indicating that the SQL was invalid at runtime or the execution continued and no data was changed.
Without knowing what the error was, we can't advise what would have caused an error. If execution continued, but the record was not (obviously) updated, then it must be because the WHERE clause of the update statement did not match any rows. You could verify this by checking mysqli_affected_rows().
The queries you have run previously wil be in the mysql general log. You might want to
echo the SQL statement to the output and check that it is populated as you expect
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm new to coding and I'm using php and mysql to make a admin panel to show clients data from a form.
Now I want to make a button to show wether the data has been processed or not.
The idea is, I have a column named star and if star == read that display "green" and if star =! read display "red".
Then if the button is pressed, if star == read update to unread but if star =! read update to read.
I have the button like this:
<td>star</td>
And read.php like this:
<?php
include("db.php");
$id = $_GET['id'];
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
header('location:admin_main.php');
?>
This just updates the row to read and doesn't have the ability to become unread again.
But I don't know how to formulate the if statements.
If anyone has any suggestions, that is much appreciated.
EDIT
To show a bit of what I tried:
I added a new column to the data sheet:
<td>".$star."</td>
And then I tried to use the code below to check the database:
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query."<br>".mysql_error());
if($selectie == 'read') {
$star = 'read';
} else {
$star = 'unread';
}
And for the read.php:
<?php
include("inc/verbinden.php");
$id = $_GET['id'];
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query." <br>".mysql_error());
if($selectie == 'read') {
$query = "UPDATE users SET star='unread' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
} else {
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!');
}
header('location:admin_main.php');
?>
But I realize that the if/else is wrong.
You're almost there. What you missed is looping over (successful) results, such as using a while loop for instance:
Side note: I added (int) for the GET array which helps to safeguard against a possible SQL injection and corrected the use of mysql_error(). That api does not intermix with the mysqli_* api.
<?php
include("inc/verbinden.php");
if(!empty($_GET['id'])){
$id = (int)$_GET['id'];
}else{
echo "The GET array is empty.";
exit; // Stops further execution.
}
$query = "SELECT star FROM users";
$selectie = mysqli_query($link, $query) or die($query." <br>".mysqli_error($link));
while($row = mysqli_fetch_array($selectie)){
if($row['star'] == 'read') {
$query = "UPDATE users SET star='unread' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!'); // use mysqli_error($link)
}else{
$query = "UPDATE users SET star='read' WHERE id = '$id'";
mysqli_query($link, $query) or die('Database error!'); // use mysqli_error($link)
}
}
header('location:admin_main.php');
exit; // Stops further execution.
Note: You could substitute mysqli_fetch_array() with mysqli_fetch_assoc().
Also, it's best to use mysqli_affected_rows() when using UPDATE in order to get actual truthness.
You can read up on those functions:
http://php.net/manual/en/mysqli-result.fetch-array.php
http://php.net/manual/en/mysqli-result.fetch-assoc.php
http://php.net/manual/en/mysqli.affected-rows.php
One thing to note though is that read and Read, as well as unread and Unread are two different animals. So make absolutely sure that those are indeed the values in your database as well is what is going in the database.
I am trying to delete a file or copy a row into a new table, depending on a $_GET.
The $_GET works fine, and I'm not including all the code, I know it isn't relevant.
The table copy works, but the select statement that gets called when the $_GET is a different value returns nothing, except when I copy the query directly into phpmyadmin.
Base code:
$pID = $_GET['pID'];
$con = mysqli_connect("...","...","...","...");
The following works:
$query = 'INSERT INTO `photos` (`id`, `photo1`, `photo2`, `demographic_id`)
SELECT `id`, `photo1`, `photo2`, `demographic_id`
FROM `photos_queue`
WHERE `photos_queue`.`demographic_id` = '.$pID;
mysqli_query($con, $query);
This does not:
$query = 'SELECT `photo1` FROM `photos_queue` WHERE `demographic_id` = '.$pID;
$result = mysqli_query($con, $query);
print($result);
unlink($result);
I've printed $query and the value of it is valid; I can copy it directly into phpmyadmin and it will work fine.
mysqli_query() doesn't return the table data, it just returns a resource that can be used to fetch it. You need to do:
$result = mysqli_query($con, $query) or die (mysqli_error($con));
$row = mysqli_fetch_assoc($result);
$filename = $row['photo1'];
print($filename);
unlink($filename);
($row = mysqli_fetch_array($result)
This should be placed after,
$result = mysqli_query($con, $query);
I'm trying to pull some information from a database, and the connection is working, but for some reason it isn't recognizing my query, even though I confirmed the query in the database with SQL and had it "generate PHP code". The echo statement is coming up blank. It's a mySQL database. Thanks for your help.
$query = "SELECT `contact` FROM `contactinfo` WHERE member=\'Henry\'";
$contact = mysqli_query($db,$query);
echo $contact;
$contact contains MySQL result object you need to fetch data from this to use this in your application.
$query = "SELECT `contact` FROM `contactinfo` WHERE member = 'Henry'";
$contact = mysqli_query($db, $query);
while ($row = mysqli_fetch_row($contact)) {
echo $row[0]; // 0 to n indicates the Column(s) Selected in SELECT Query
}