I am doing a little bit of learning on mysql, php and the like. I'm using a shared hosting plan so am quite limited from a settings changes point of view.
I am attempting to run a simple mysql select command through PHP, but all i get back is a blank error
<?php
$typeID = $_GET['tid'];
//variables for the database server
$server = "localhost";
$user = "codingma_rbstock";
$pwd = "M#nL%V{%RI+h";
$db = "codingma_rbstock";
//variables for the database fields
$itemNo;
$itemNm;
$itemDesc;
$buyPr;
$sellPr;
$quan;
$dept;
//database connection
//create connection
$conn = new mysqli($server, $user, $pwd, $db);
//if the connection fails throw an error.
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
}
echo "Welcome to " . $typeID . "<br>";
$sql = "select ITEM_NAME from stock where ITEM_NO='00001'";
if ($conn->query($sql) === TRUE){
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
}else{
echo "Error: " .$sql . "<br>" . $conn->error;
}
echo $res;
?>
I have checked and it seems to be connecting to the database fine (I changed a few account details to see if that threw a different error and it did).
I am sure I am missing something completely obvious here! The below is the text output from the error;
Error: select ITEM_NAME from stock where ITEM_NO='00001'
Thanks for any help.
your problem is in this line
if ($conn->query($sql) === TRUE){
you are doing a variable type check ( === ), the result of that comparision will always fail because, for as long as you have data in your table and your query doesn't fail $conn->query($sql) will not return a boolean value
mysqli::query documentation says:
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.
You are using here a SELECT, therefore a successfull result won't be boolean
Try switching to
if ($conn->query($sql) == TRUE){
Or even better remove that if completely
EDIT
The better approach for that part of the code is:
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
if ($res === false) {
echo "Error: " .$sql . "<br>" . $conn->error;
}
Related
I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>
I'm currently learning MySql, but ive hit this problem.
the following code should just query the db for everything in the users table. but it returns this error. Error: SELECT * FROM users which helps me not at all. I am able to successfully insert an item into the database, but I am unable to select from it. I've also tried $sql = "SELECT * FROM ama.users"; my DB structure is
ama
|-users
any help would be much appreciated.
$conn = new mysqli($_ENV['OPENSHIFT_MYSQL_DB_HOST'],$_ENV['OPENSHIFT_MYSQL_DB_USERNAME'], $_ENV['OPENSHIFT_MYSQL_DB_PASSWORD'], 'ama');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = "Doe";
$password = "johnexample";
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
From the PHP Manual:
mysqli::query will return object in success and return false in failure.
So you can use it without checking data type (===):
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
For more better understanding you can use var_dump() and check what are you getting like:
var_dump($conn->query($sql));
Documentation says:
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.
So, do something like
$result= $db->query($sql);
and then check the rows in $result
i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .
I have XAMPP and I want to write a simple PHP page, that redirects me to the link that I specify, and also saves the link in an SQL database.
Let's say I want to visit www.google.com:
I'd visit something like:
localhost:80/redirect.php?url=https://google.com
And PHP would redirect me there and also save the www.google.com link in an SQL table.
Can you help me out?
Considering how you formed your question, it looks as if you had an idea an just want someone to give you the solution without you even making an effort (please correct me if I'm wrong but that's how it seams...)
The task you are trying to achieve is a simple one, and it's only fair to point you in the right direction. your "task" can be broken into several smaller ones:
Create database / table for storing data | PHP Create MySQL Tables
Get URL parameter in PHP
PHP Insert Data Into MySQL
How to make a redirect in PHP
Sorry if this is not the kind-a answer you are looking for, but I figure the point of this website is for people to learn something and not just copy+paste. The provided links can be used to solve your task problem.
This is what I came up with, after MySQLi Object-oriented did not validate this:
$sql = "SELECT * FROM logging WHERE link=$link";
if ($conn->query($sql) === TRUE) {}
It still increments the number of visits sometimes by +2. I don't know why.
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$datetime = date_create()->format('Y-m-d H:i:s');
$datetime = "'".$datetime."'";
$link_clean = $_GET['link'];
$link = "'".$link_clean."'";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM logging WHERE link=$link";
if ($result = mysqli_query($conn, $sql))
{
if(mysqli_num_rows($result)>0)
{
$sql="UPDATE logging SET last_visit_date = $datetime, visit_count = visit_count + 1 WHERE link=$link";
if (mysqli_query($conn, $sql)) {
$conn->close();
header("Location: https://$link_clean");
exit;
} else {
echo "1Error: " . $sql . "<br>" . mysqli_error($conn);
$conn->close();
exit;
}
}
else
{
$sql="INSERT INTO logging (link, last_visit_date, visit_count) VALUES ($link , $datetime , 1)";
if (mysqli_query($conn, $sql)) {
mysqli_close($conn);
header("Location: https://$link_clean");
exit;
} else {
echo "2Error: " . $sql . "<br>" . mysqli_error($conn);
mysqli_close($conn);
exit;
}
}
}
else
{
echo "3Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I am not actually very good at it, but I never got this kind of error. I am trying to select GB entries and I can't get it working.
gb.php
<?php
$conn = new mysqli('localhost','ab','somepassword','gb');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
else {echo 'connected';}
$sql = "SELECT * FROM `posts`";
if ($conn->query($sql) === TRUE) {
echo 'done';
}
else{echo 'sql not working';}
?>
Table snapshot
Result:
connectedsql not working
One more thing the INSERT & UPDATE statements are working from same folder.
The return value of MySqlI->query() is defined like:
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.
So you must check for not equal to false
if ($result !== false) {
you can also check on this condition
$res=$conn->query($sql);
if($res)
{
}
else
{
}
mysqli_query/ $mysqli->query does not return True if the query executed succesfully but return false if not executed..Try with -
$result = $conn->query($sql);
if ($result !== false) {
echo 'done';
}
else{echo 'sql not working';}