In this code I have used the prepared statement query, I want number of rows but in following code it returns me zero rows. plz tell me what is wrong in my code.
$servername = "localhost";
$username = "root";
$password = "";
$dbname="lamp";
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$contactno=mysqli_real_escape_string($conn,$_POST['contactno']);
$description=mysqli_real_escape_string($conn,$_POST['description']);
$email=mysqli_real_escape_string($conn,$_POST['contactemail']);
$subject=mysqli_real_escape_string($conn,$_POST['subject']);
$creationdate=mysqli_real_escape_string($conn,$_POST['creationdate']);
if(isset($_POST['status1']))
{
$status =$_POST['status1'];
}
if(isset($_POST['noteid']))
{
$id = mysqli_real_escape_string($conn,$_POST['noteid']);
}
$stmt=$conn->prepare("update notifications set subject=?,description=?
,status=?, creationdate=?,contactno=?,contactemail=? where id=? "); $stmt->bind_param("ssisisi",$subject,$description,$status,$creationdate,$contactno,$email,$id);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >0)
{
echo "sucess";
header("Location: updategovermentnotification.php");
}
Since UPDATE query returns only true or false based on successful execution, so you need to do like below:-
need to use if(mysqli_affected_rows($conn)>0){ instead of if($stmt->num_rows >0){
OR
if($stmt->execute()){ $stmt->store_result();echo "sucess";header("Location: updategovermentnotification.php");}
The mysqli_stmt property you are looking for is $affected_rows. It contains the number of rows affected by an INSERT, UPDATE or DELETE statement.
The property $num_rows contains the number of rows returned by a SELECT query.
Related
I am trying to create a simple echo from a SELECT from DB.
It echos blank always.
Here is the code:
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "xxxx";
$conn = mysqli_connect($hostname, $username, $password, "xxxx");
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$user = $_GET['user'];
$pass = $_GET['pass'];
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$retval = mysqli_query($conn, $sql);
echo($retval);
mysqli_close($conn);
?>
It would be greatly appreciated if someone could help and tell me what I am doing incorrectly :)
If it worked, you didn't get ID back, but a "mysqli_result" object.
Try print_r($retval) to see what you really got.
If it's a mysqli_result object, you need another step to get the data.
while ($row = $retval->fetch_assoc()) {
echo $row['id'];
}
According to the manual:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return TRUE.
Moreover, please note that a query that runs but returns zero results is still considered a "successful query" since the query did run in the database and an empty result set is a legitimate response. This means the query will still return a mysqli_result object.
As I understood the code so far, if you want to echo results returned you could use mysqli_fetch_array(), so your code would become:
/* numeric array */
$row = mysqli_fetch_array($retval, MYSQLI_NUM);
And you can echo it as:
echo $row[0];
or
/* associative array */
$row = mysqli_fetch_array($retval, MYSQLI_ASSOC);
And then you could echo as:
echo $row['id'];
Furthermore, you can use mysqli_fetch_assoc() to loop over your results or for fetching single row instance purposes, an example is:
while ($row = $result->fetch_assoc()) {
echo $row['id'];
}
Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in the resultset.
And if you want to check if your query has found any rows, you can use mysqli_num_rows
Which works as the following:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($retval);
Do you know if you are connected to the database or not? You could try changing a value to see if the error comes up or not.
If thats not the issue this should work better:
$host = 'xxxx';
$user = 'xxxx';
$pass = 'xxxx';
$db = 'xxxx';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$whateverString = $row['cakes'];
}
echo $whateverString;
Now lets say that you had a value in the mysql row called cakes that is equals to 5 then it will fetch that specific string from the row if the user and pass is correct.
So the value above will output "5" if the mysql value 'cakes' is 5.
Thanks for your answers, people!
I ended up with this:
$q=mysqli_query($con,"SELECT id FROM `users` WHERE user='$username' and pass='$password'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if(json_encode($data)== '[]'){
echo 'error';
}else {
echo json_encode($data);
}
?>
I'm trying to echo a phone number from my database using php but it keeps returning blank. I've been fiddling around with it all night and looking at various examples but I've not been able to get it to work. Can someone help me please?
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT phone FROM users WHERE ID = 29' ;
$results = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($results);
echo $row['phone'];
Since your using mysqli_fetch_row it returns result enumerated array which means it returns the result row array staring from 0 offset.
Reference : http://php.net/manual/en/mysqli-result.fetch-row.php
ie.
$row = mysqli_fetch_row($results);
//Now $row columns can be accessed by $row[0] $row[1] and so on.
On the other hand if you use mysqli_fetch_assoc then the result will be returned as associative array ie key value pairs
Reference : http://php.net/manual/en/mysqli-result.fetch-assoc.php
ie.
$row = mysqli_fetch_assoc($results);
//Now you can use $row as $row['phone'], $row['id'] and so on
I am trying to compare a MySQL table column which I have imported to my script and compare it with a PHP value which I have defined.
I am trying to make an if loop that checks if any of the values in the column are equal to the variable.
// Connect to database containing order information
$servername = "server";
$username = "user";
$password = "pass";
// Create connection
$conn = new mysqli($servername,$username,$password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$name = $ordernumber = "";
// Load up data from the form
$ordernumber = ($_POST['order_number']);
// Get SQL info
$sql = "SELECT order_number FROM p_orders;";
if ($conn->query($sql) === TRUE)
{
echo "Checked Orders.....";
}
else
{
echo "Failed to check orders, please contact Support for assistance" . $conn->error;
}
// Checking Script
if ($ordernumber === $orders)
{
echo "Order Number Found.... Let's Select a Seat";
}
else
{
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
};
The end part of the script should be like this...
$stmt = $mysqli->stmt_init();
if ($stmt->prepare('SELECT order_number FROM p_orders WHERE orderID = ?')) {
$stmt->bind_param('s',$_POST['order_number']); // i if order number is int
$stmt->execute();
$stmt->bind_result($order_number);
$stmt->fetch();
if (!empty($order_number))
echo "Order Number Found.... Let's Select a Seat";
}else {
echo "Your Order was not found...";
}
$stmt->close();
}
$mysqli->close();
...note that the query now looks for only the records that match and note the use of prepared statement to make safe the post variable from SQL Injection.
The reason to collect only the matching items from SQL is otherwise, if you have a million records, the database would return all of them and then PHP will need to loop through them (this can cause maximum execution, memory and other errors). Instead databases where built to look things up like this - note an index on this field would be good and also use of a "youtube style" id is recommended, which is why I've assumed the use of a string for it's instead of a number as the variable minght imply - and it's not the "id" which is good for a number of reasons... I've added a link to explain "youtube style" id which I'll not go into detail here but there is a lot of win in using that :)
UPDATED based on...
http://php.net/manual/en/mysqli-stmt.prepare.php
MySQL prepared statement vs normal query. Gains & Losses
https://www.youtube.com/watch?v=gocwRvLhDf8 (Will YouTube Ever Run Out Of Video IDs?)
Preferably use a WHERE clause searching for the order id and mysqli prepared statement, like below.
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = "";
// Load up data from the form
$ordernumber = $_POST['order_number'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM p_orders WHERE orderID=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $ordernumber ); // "i" if order number is integer, "s" if string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($counter);
/* fetch value */
$stmt->fetch();
if ($counter>0) { // if order id is in array or id's
echo "Order Number Found.... Let's Select a Seat";
} else {
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>
So I am just doing a simple email verification for testing/learning purposes, however I cannot figure out what is wrong. Here is the problem:
The query works.. it updates the field in my table, but it should only do so if it active=0. So basically, it still echo's "success" even if active=1, which it should not be able to query, because its only supposed to grab WHERE active=0 ... this make sense? Here take a look
<?php
$connection = new mysqli('localhost', 'user', 'pass', 'db');
if (mysqli_connect_errno()) {
printf("Can't connect to MySQL Server. Errorcode: %s\n",
mysqli_connect_error());
exit;
}
$email = $_GET['email'];
$activation = $_GET['hash'];
$query = $connection->query("UPDATE users SET active = '1' WHERE
email='".$email."' AND activationCode='".$activation."' AND active='0'");
if ($query){
echo "success";
} else {
echo "fail";
}
$connection->close();
?>
The query returns true because the query was executed just fine, even if it didn't affect any rows. It only returns false if the query is invalid. You should look into retrieving the number of affected rows. (mysql_num_rows($query) for example.)
Also, you should use mysql_real_escape_string($getvalue) when using values from $_GET or $_POST in your queries to prevent MySQL injection.