MySqli Select is not working - php

I couldn't figure out why it has some problem like this. The error displayed mysqli_fetch_assoc() expects parameter 1 to be mysqli_result.
My code is like this. I don't know which one is wrong.
Have a look at my con.php.
<?php
$conn = mysqli_connect('localhost', 'username', 'password');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
and this is my page.php
<?php
include 'con.php';
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";
Any ideas? Appreciate any answers from you. Cheers!

I think I figured it out:
Change $result = mysqli_query($link,$query);
to $result = mysqli_query($conn,$query); since $conn is your DB connection, not $link
as per what you posted above
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
and remove:
$link = mysqli_connect('localhost', 'username', 'password', 'username') or die("Error " . mysqli_error($link));
since you're already loading your DB con with include 'con.php';
Or this way:
<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name') or die("Error " . mysqli_error($conn));
$query = " SELECT thread_id, thread_name, thread_date
FROM forum_thread
ORDER BY thread_date";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)) {
$thread_id = $row ['thread_id'];
$thread_name = $row['thread_name'];
$thread_date = $row['thread_date'];
echo "$thread_id, $thread_name, $thread_date";

The error message indicates the query did fail for some reason. Instead of just using $result test to see if it's valid and if not output the error to the screen or a log file:
if ($result) {
// continue processing $result
}
else {
echo mysqli_error($link);
}
Edit:
The 4th parameter in the mysqli_connect should be the name of the database, "abc" or whatever.

Try to use following code
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
Here when you try to get connection object itself you can identify the problem if something goes wrong.

Related

Why won't this php SELECT FROM query work?

Here is my simple php code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "********"; //hiding my password
$dbname = "course";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM tutors";
$result = $conn->query($sql);
if( $result === true ) {
echo "good";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
?>
</body>
</html>
In my database called "course", I have a table called "tutors" which has a column called "name". I have two entries in that table with the names "deep thought" and "pyrenees" respectively.
When this code runs however, the only thing that prints out is:
Error: SELECT name FROM tutors
It is supposed to simply print out the two names that I mentioned before.
Does anyone know why this happens? I know for a fact that I have the two entries in my table!
I think the word "name" is a MySQL reserved word. Wrap your query variables in a tilde backticks like this:
$sql = "SELECT `name` FROM `tutors`";
This helps to escape those values from MySQL thinking you're trying to referencing a built in variable.
Why not use mysqli like so:
function getFollowers($link, $userid)
{
$sql = "SELECT users.id, username, profileImg FROM following INNER JOIN users ON users.id = following.userid WHERE followid = " . $userid;
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
$resultsArray[] = $row;
}
mysqli_free_result($result);
return $resultsArray;
}
This is just a clean example, I am sure you get the idea.
Here is what $link is
function connection()
{
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
return $link;
}
Or without the methods:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'databaseTable');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT name FROM tutors";
$result = mysqli_query($link,$sql);
$resultsArray = [];
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}
mysqli_free_result($result);
To check if the query was successful you can do this:
if (mysqli_num_rows($result) > 0)
{
//has rows, so whatever you want with them.
}
You put the condition after defining $result.

PHP and mysql connection not working

I have written following code to connect mysql in php but I am not getting output.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if ($mysql_conn->connect_error) {
die("Connection failed: ". $mysql_conn->connect_error);
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysql_select_db('yieldofvanillin', $mysql_conn);
if (!$db_selected){
die ('Can\'t use : ' . mysql_error());
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = $mysql_query($query);
while ($line = myql_fetch_array($result, MYSQL_ASSOC)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysql_close($mysql_conn);
?>
The database name is "yieldofvanillin" and it has five column. I an getting output Connected successfully. After that no output. Please let me know the bug in code.
i have remove errors. which i mention in comments. Code Reference PHP Manual. you should read this manual (strongly recommended)
<?php
$mysqli = new mysqli("localhost", "root", "pravin", "yieldofvanillin");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
echo $row["products"];
echo $row["Microorganism"];
echo $row["yield"];
echo $row["Reference"];
}
/* free result set */
$result->free();
}
you're mixing mysqli and mysql libraries.
the code should be:
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if (mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysqli_select_db($mysql_conn,'yieldofvanillin');
if (!$db_selected){
die ('Can\'t use : ' . mysqli_error($mysql_conn));
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = mysqli_query( $mysql_conn,$query);
while ($line = mysqli_fetch_assoc($result)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysqli_close($mysql_conn);
?>
Remove error in your code.Read carefully php manual.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$db = "yieldofvanillin";
// Create connection
$mysqli = new mysqli($servername, $username, $password, $db);
/* connection string*/
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
}
$result->free();
}
$mysqli->close();
?>
Your output not showing because mysql_fetch_array is not correct.Because you are mixing mysql_ and mysqli_ functions and you called myql_fetch_array that doesn't exist in mysqli. MySQL and MySQLi are two different PHP extensions and they cannot be mixed. Because the former is deprecated in mysqli

SQLi Error when trying to echo a certain ID in PHP

I am making a status update page for practicing PHP and MySQL.
I am currently trying to echo the saved status on the page.
The statuses are saved in a row called "Status" and they are all given a certain ID in a row called "statusID."
The problem I am having is which fetch I want to use because converting it into a string using (string)$var doesn't work. ($var is an example).
Also, the $idNum variable is something for later use, shouldn't have anything to do with this.
Here is the code: (Obviously the first variables are censored so none tries to connect to the database, the connection working in the actual code.)
The problem lies in the $fetchRes I believe.
<?php
$idNum = 1;
$servername = "censored";
$username = "censored";
$password = "censored";
$db_name = "censored";
$conn = mysqli_connect($servername, $username, $password, $db_name);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Status FROM SavedStatuses WHERE statusID=1;";
$statusQuery = mysqli_query($conn, $sql);
$fetchRes = mysqli_fetch_assoc($statusQuery);
if($conn->query($sql) == TRUE)
{
echo $fetchRes;
} else {
echo "Failed to retrieve status, error: " . $conn->error;
}
?>
As I mentioned in comments, you are querying twice and not looping over (successful) results.
A "loop" is to use either a while or a foreach. I used a while loop for this example.
From the "official" manual:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
So in your case, your code would read as:
Sidenote: Status and status are two different animals, so make sure the letter case matches (in the loop).
<?php
$mysqli = new mysqli("censored", "censored", "censored", "censored");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Status FROM SavedStatuses WHERE statusID=1";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Status"];
}
/* free result set */
$result->free();
}else{
echo "The query failed: " . mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
?>

Calling MySQL Stored Procedure through PHP

I've installed XAMPP and have been attempting to interrogate my database using PHP although I keep getting the same error.
<?php
$servername = "localhost";
$username = "root";
$password = "secret";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform queries
$result = mysqli_query($conn,
"use edgeserver; call ShowAll") or die("Query fail: " . mysqli_error());
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
$conn->close();
?>
However this presents me with the following error:
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\amit\ShowAll.php on line 16
Query fail:
Mysql_error requires db connection to be passed. Try below:
mysqli_error($conn);
Thanks, it ended up being a combination of what you both said:
<?php
// Create connection
$conn = new mysqli('localhost', 'root', 'secret', 'edgeserver');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform queries
$result = mysqli_query($conn,
"call ShowAll") or die("Query fail: " . mysqli_error($conn));
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
$conn->close();
Great response, hopefully this will be the base to me developing some good code.
I think the problem is from use edgeserver; call ShowAll.
use edgeserver, where edgeserver is the database that you want to use.
call ShowAll - what you try to accomplish with this?
Your new mysqli must be like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
source: http://php.net/manual/ro/mysqli.construct.php
And on mysqli_query you must do the queries like "Select * from table".

Mysqli num row returned is not working

I'm wondering why it is not working for mysqli eventhou mysql_num_row is working.
if (mysql_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
That is mysql. But, Im trying convert it to mysqli.
if (mysqli_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
It supposed to be displayed on the screen but it's not. And there is nothing error message displayed. Or am I missing something? Any ideas?
First, a quick tutorial on some of the differences between mysql_* and mysqli_* functions.
In mysql_* you would have 3 parameters for your DB connection, then have a seperate line for your DB selection.
For example:
$db = mysql_connect("host","username", "password");
$db_selected = mysql_select_db('db_name', $db);
if (!$db_selected) {
die ('Can\'t use this : ' . mysql_error());
}
Your query would come first, followed by your DB connection.
For example:
mysql_query($query,$db);
But in mysqli_* things have changed including the parameters location. You now put all 4 parameters, for example (if you haven't done so yet):
$db = new mysqli("host","username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
then the DB connection would come first, followed by the query instead of the other way around:
mysqli_query($db,$query);
A sample query:
$email = mysqli_real_escape_string($db,$_POST['email']);
$query = mysqli_query($db, "SELECT * FROM table_name WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
$sql="INSERT INTO table_name (email) VALUES ('$email')";
if (!mysqli_query($db,$sql))
{
die('Error: ' . mysqli_error($db));
}
}
You could try this code:
$connect = new mysqli("localhost", "user", "password", "database");
$query = "SELECT name FROM table";
$statement= mysqli_prepare($connect, $query)
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
if (mysqli_stmt_num_rows($statement) > 0) {
echo "<p>That name has been taken </p>";
}
mysqli_stmt_close($statement);
mysqli_close($connect);

Categories