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
Related
I am trying to develop a registration form.
When I fill all the filed and submit the form, no error showing
the server is connected but no data on mysql database table. Bellow L attached the action file of form. What do I miss? and how can I solve it?
<?php
$mysqli_servername = "localhost";
$mysqli_username = "admin_try";
$mysqli_password = "rFT5hePS5u";
$mysqli_database = "indepe";
// Create connection
$conn = mysqli_connect($mysqli_servername,$mysqli_username,$mysqli_password,$mysqli_database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'>Back to main page</a>";
if (isset($_GET["submitreg"]))
{
$id= mysqli_real_escape_string($conn, $_POST['id']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$re_password = mysqli_real_escape_string($conn,$_POST['re_password']);
$compnay = mysqli_real_escape_string($conn,$_POST['compnay']);
$contact = mysqli_real_escape_string($conn,$_POST['contact']);
$tell = mysqli_real_escape_string($conn,$_POST['tell']);
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell);
VALUES('id','$country','$email','$password','$re_password','$compnay','$contact'),'$tell'";
if ($conn->query($sql) === TRUE) {
echo "record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if (mysqli_query($conn, $sql)) {
echo " record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
//$conn->close();
mysqli_close($conn);
?>
There are few errors in your insert query
Remove the semicolen after tell in your insert query
You gave id in values instead of $id
$tell is outside the bracket
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell) VALUES('$id','$country','$email','$password','$re_password','$compnay','$contact','$tell'");
Im not sure whether that is your problem or it occured your copying your code..because no error was shown
I think you mistake in insert query remove semicolon before VALUES keyword and if id column auto increment then no need to add it in insert query otherwise you need add it properly and ,'$tell' is outside the bracket please make it proper
$sql = "INSERT INTO registration(country,email,password,re_password,compnay,contact,tell) VALUES ('$country','$email','$password','$re_password','$compnay','$contact','$tell')";
I thing you need to add privileges to particular user to insert records. as you have declared $mysqli_username = "admin_try";. now go to localhost/phpmyadmin and then add privileges to particular user!!
You are using $_GET check and for submitting the form which is wrong. It's always recommened to do POST request for form submission.
if (isset($_GET["submitreg"]))
But, later in your code to get the the data you are using $_POST.
$id= mysqli_real_escape_string($conn, $_POST['id']);
Please check your form method in html make it POST and change
if (isset($_GET["submitreg"]))
to
if (isset($_POST["submitreg"]))
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;
}
I have a question about this code.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
As far as a I know $conn -> query()call a method query attached to the object $conn. How can we compare a method with ===True?
From query command documentation:
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.
In other words it will return TRUE if insert was successful and FALSE otherwise. So we are comparing function return value after its execution with TRUE to see if it has successfully executed.
You can rewrite this as:
$query_sucessfully_executed = $conn->query($sql);
if ($query_sucessfully_executed) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
It has the same meaning. I hope this clears things up a bit.
You can learn more about this in query documentation.
I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone
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);
?>