Cannot select from table, but I can insert and create? - php

I have this extremely weird issue with mysql. I can insert into, and create tables. However I cannot select anything and it does not display any error when I try, it just echos my line "Error: "
getDiff("validTable");
function getDiff($regNr) {
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//todo
$sql = "SELECT * FROM $regNr ORDER BY id LIMIT 1";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "done";
} else {
$error = $result->error;
echo "Error: " . $error;
}
$conn->close();
}
But when I insert to the DB using this
$query = "CREATE TABLE IF NOT EXISTS $regNr ( `id` MEDIUMINT NOT NULL AUTO_INCREMENT, `mail` INT NOT NULL , `price` INT NOT NULL , `views` INT NOT NULL , `the_date` DATE NOT NULL , `time` VARCHAR(5) NOT NULL, PRIMARY KEY (id) )";
runQuery($query);
function runQuery($todo) {
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//todo
$sql = $todo;
if ($conn->query($sql) === TRUE) {
echo "done";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
}
It works just fine and dandy. WHAT HAVE I DONE WRONG?! This is driving me crazy!

It shows only "Error" because your query succeeds and returns a mysql object which is not equal to True and therefore it does not echo done
See (http://php.net/manual/en/mysqli.query.php)
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.
Change your code with the code below to make it work:
if ($conn->query($sql) === FALSE) {
echo "Error: " . $conn->error;
} else {
echo "done";
}
Basically turning the if around such that it checks for FALSE or not FALSE.
Most probably you also want to store the result in a variable like:
if ($result = $conn->query($sql) === FALSE) {
And later on use $row = $result->fetch_array() or $row = $result_fetch_assoc() to get the data.

mysqli_query
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.
As per this condition
if ($conn->query($sql) === TRUE) {
You get mysqli_result from your query and this is not equal to TRUE and you always goes into error condition
To fetch data from query use fetch_array
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0]);
To get error form query we use $conn->error not $result->error it need your connection variable not your result variable
Read http://php.net/manual/en/mysqli.error.php

Related

Unable to select data from MySQL database using PHP 7.2

Please I haven't quite figured out what's wrong with this code
<?php $servername = "blee.com";
$username= "free";
$password = "free";
$dbname = "one";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "success";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close(); ?>
Somehow, if I try to insert anything into the database, it works perfectly, but if I try to select, it just shows "error creating table :" with no error being displayed...... I've searched all over but found no solution
I'm using php7.2 on my web server
For SELECT (as well as SHOW, DESCRIBE and EXPLAIN) queries mysqli::query returns a mysqli::result object if it succeeds, not a boolean. So your test
if ($conn->query($sql) === TRUE)
will always fail. What you should do instead is check that the query didn't fail (by comparing the return value with false), then you can use the returned object to fetch rows from the result set by using functions such as mysqli_result::fetch_assoc.
$result = $conn->query($sql);
if ($result !== false) {
// do something with results e.g.
// while ($row = $result->fetch_assoc()) { print_r($row); }
}

How to know Update is done for in simple mysqli query , Updated at least one row

My Code is :
//Catch
$myotp=$_GET["myotp"];
$rowid=$_GET["rowid"];
//Constructing the updat esql query
$update= "update order set dsotp ='$myotp' WHERE fsotp='$myotp' and id_order=$rowid";
//Excecuting the query
$res=mysqli_query($conn,$update);
It is working fine. But the problem is how to know from PHP code that it is updated the table?
You can check this way:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
Refer:https://www.w3schools.com/php/php_mysql_update.asp
mysqli_query returns TRUE or FALSE. and also the result set.
So, you can try this:
print_r($res);
PS: Also for the second part you can use mysqli_affected_rows($conn); to get the number of affected rows.
If you want to test if the query executed succesfully you should use the if statements provided above, however these do not check if there was any value updated. If you want that, you should use affected_rows.
http://php.net/manual/en/mysqli.affected-rows.php
A basic example would be this:
if($result = $mysqli->query($sql)){
var_dump($mysqli->affected_rows);
if($mysqli->affected_rows == 1){
return TRUE;
} else{
return FALSE;
}
}

SELECT COUNT if statement

Ok, so it seems like my SELECT count query doesn't work here:
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submitted1'])) {
$result= mysqli_query("SELECT COUNT (Motspillerid)
FROM SESSION
WHERE Motspillerid= 3 ");
echo $result ;
} else {
echo "Wrong" ;
}
?>
And when I press submitt nothing happens, I don't get any error message and I don't get the result. So it's something wrong with the SELECT query I guess.
I'm noob I know, I'm new to this.
:)
You're not calling mysqli_query() correctly, the first argument has to be the database connection object returned by mysqli_connect.
And after performing the query, you have to fetch the results using one of the mysqli_fetch_X() functions.
if (isset($_POST['submitted1'])) {
$result= mysqli_query($conn, "SELECT COUNT(*) AS count
FROM SESSION
WHERE Motspillerid= 3 ");
$row = mysqli_fetch_assoc($result);
echo $row['count'];
} else {
echo "Wrong" ;
}

Two queries in one php file, one is not working - why?

In my code, there are two different queries. The first one is working - by which I mean it goes to the if path. The problem is with the second one which goes to the else path.
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
if ($conn->query($sqlmodeid_uderid) === TRUE) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
$conn->close();
Help me out. (query is working fine)
The condition is a problem:
$conn->query($sqlmodeid_uderid) === TRUE
If we consult the documentation for the query function we will see:
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.
As you are dealing with a SELECT query, this call will never return true. It will return a mysqli_result object on success, and false on failure.
Instead you could rewrite this condition in a number of ways.
Check the query does not return false.
if ($conn->query($sqlmodeid_uderid) !== FALSE) {
Use == instead of ===. The first will cast between two different types (and the mysqli_result object will equate to true when casted to bool) whereas === performs a typesafe comparison, meaning the condition will only be satisfied if both operands are of the same type and have the same value.
if ($conn->query($sqlmodeid_uderid) == TRUE) {
The same logic in point 2 can be wrote in a few different ways:
if ($conn->query($sqlmodeid_uderid)) {
if ((bool)$conn->query($sqlmodeid_uderid)) {
I would look at the php.net documentation on comparison operators for more info on this:
http://php.net/manual/en/language.operators.comparison.php
Use code like this...
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
For the second query, I think you should do like this instead of doing "=== TRUE"
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
/* Select queries return a resultset */
if ($result = $conn->query($sqlmodeid_uderid)) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
Look at the examples in the doc : http://php.net/manual/en/mysqli.query.php

PHP creating 2 rows and not checking input

What I'm trying to do is make a username (just username) get sent to a MySQL database, if it isn't already there.
Basically, I'm getting the input, checking it against all other rows in my username column, and, if the input is not the same as any of them, then add the input to the database. Here is my code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
No error is reported, but it simply creates the data twice, and doesn't check the input. I can't see how. This is how I've tried. It looks logical that is should work, but it's not. Why?
I'm using MySqli Object-Orientated
Try this code...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT IGNORE INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
echo "New record created successfully";
}else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
You are executing the $conn->query($sql) twice. The first one is in $result = $conn->query($sql); and the second if ($conn->query($sql) === TRUE). That is why you get 2 entries in the for one request.
First check for the user you are prepering to insert and if it returns 0 statements then go with the second if you have wrote.
Edit 2:
Try use PDO:
The code will look something like this:
if( isset( $_POST["submit"] ) ) {
$stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ?");
$stmt->execute( array( $_POST["username"] ) );
$_results = $stmt->get_result();
if( count( $_results ) > 0 ) {
die("Error, please consult an admin!");
} else {
$stmt = $pdo->prepare('INSERT INTO users (username) VALUES( ? )' );
$stmt->bindParam( 1, $_POST['username'] );
if( $stmt->execute() ) {
echo 'Success';
} else {
echo 'Whoops, you have an error mate!';
}
}
}
Hope it helps

Categories