Small section of PHP/mysql code dies. Not sure why - php

I rarely do programming. I only know enough to be dangerous as they say and I simply assemble bits of code to get what I want. My code below seems to die at the $sql query statement. It never returns any data. It should show the 13 records that are present, but it says there is none to return. I'm guessing this is some kind of syntax error?
<?php
$host = 'myipaddress';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$conn = mysql_connect($host, $user, $pass, $db) or die("Can not connect." . mysql_error());
// Create connection
//$conn = mysqli_connect($host, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Connection failed: ");
}
$sql = "SELECT * FROM pages WHERE pid > '5'";
$result = mysql_query($conn, $sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysql_close($conn);
?>

Your using the mysql_ API right up until you try to fetch rows here, where you're using mysqli_. That will not work.
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
Your script is at risk for SQL Injection Attacks. Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
EDIT: Your connection (Good Eyes Ralph!) string will not work because mysql_connect() doesn't accept the database as part of the connection. You must use the additional function mysql_select_db() to choose your database.
In addition, it is not necessary to specify the connection link in mysql_query() but if you do it should be the second argument:
$result = mysql_query($sql, $conn);

There is quite a bit wrong with your code.
mysql_connect($host, $user, $pass, $db)
mysql_connect() uses 3 parameters, the 4th doesn't do what you think it does.
http://php.net/manual/en/function.mysql-connect.php
You need to use mysql_select_db() http://php.net/manual/en/function.mysql-select-db.php
Then,
$result = mysql_query($conn, $sql);
The connection comes second in mysql_.
http://php.net/manual/en/function.mysql-query.php
Then you're mixing a MySQLi function mysqli_fetch_assoc which doesn't intermix with the mysql_ library.
Read: Can I mix MySQL APIs in PHP?
So, just use the full MySQLi library
http://php.net/manual/en/book.mysqli.php
or PDO:
http://php.net/manual/en/book.pdo.php
Along with a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Check for the real errors, should your query fail:
http://php.net/manual/en/function.mysql-error.php
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: Displaying errors should only be done in staging, and never production.
As you can see, I did not provide you with a full rewrite, as I feel that in "Teaching a person how to fish...", will feed them for life, rather than "Throwing them a fish...", and only feed them for a day (wink).

You need to use mysql_fetch_assoc() in place of mysqli_fetch_assoc(), because your previous functions are based on mysql_*, not mysqli_*
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}

Related

Converting from mysql _query to mysqli_query [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 years ago.
I have many simple PHP files with MySQL queries that I need to modify since my webhost migrated from PHP5 -> PHP7. I am pretty much a PHP/MySQL beginner trying to wrap my head around the changes from MySQL to MySQLi.
I've begun reading the PHP docs re: MySQLi but am getting stuck on mysqli_query at the moment.
Here is the MySQLi code I've tried so far:
<?php
$con = mysqli_connect("localhost”, “my_user","my_password,"my_db”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$result = mysqli_query("SELECT image, caption
FROM tbllinkcat, tblimages
WHERE tbllinkcat.catid = tblimages.catid
AND tbllinkcat.catid=1;");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysql_close($con);
?>
I'm pretty sure the mysqli_connect code is working but I get errors on the mysqli_query code (error: Warning: mysqli_query() expects at least 2 parameters.
And I am pretty sure I will get errors on the mysql_fetch_array too once I correct mysqli_query. So for now I was wondering if someone could just show me an example of a mysqli_query that would work for the specific SQL statements in my code above? I will continue reading the PHP docs for MySQli and mysqli_query. Thank you.
mysqli_query needs two parameters:
Your database connection
A query
That will result in this:
$result = mysqli_query($con, "SELECT image, caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1;");
You also have some weird looking quotation marks in your connect function, correct them:
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
To fetch the array, you would use:
while($row = mysqli_fetch_assoc($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
And finally, to close the connection:
mysqli_close($con);
Note: Just so you know, when using queries with user input, please use prepared statements and bind_param. This will prevent SQL injection attacks. I will show and example below.
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$result = $stmt->execute();
<?php
$con = mysqli_connect("localhost”,“my_user","my_password”,"my_db”);
//establish database connection
if (!$con)
{
die('Could not connect:'.mysqli_error());
}
$result = mysqli_query($con,"SELECT image,caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1");
//perform sql select query with database connection
while($row = mysqli_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysqli_close($con);
?>
For More Info read :-https://www.php.net/manual/en/mysqli.query.php

Can't fetch data from database table.... 500 error

I have tried a ton of different versions of this code, from tons of different websites. I am entirely confused why this isn't working. Even copy and pasted code wont work. I am fairly new to PHP and MySQL, but have done a decent amount of HTML, CSS, and JS so I am not super new to code in general, but I am still a beginner
Here is what I have. I am trying to fetch data from a database to compare it to user entered data from the last page (essentially a login thing). I haven't even gotten to the comparison part yet because I can't fetch information, all I am getting is a 500 error code in chrome's debug window. I am completely clueless on this because everything I have read says this should be completely fine.
I'm completely worn out from this, it's been frustrating me to no end. Hopefully someone here can help. For the record, it connects just fine, its the minute I try to use the $sql variable that everything falls apart. I'm doing this on Godaddy hosting, if that means anything.
<?php
$servername = "localhost";
$username = "joemama198";
$pass = "Password";
$dbname = "EmployeeTimesheet";
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
$sql = 'SELECT Name FROM Employee List';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["Name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
There be trouble here:
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
There are three problems here:
mysqli_conect() instead of mysqli_connect() (note the double n in connect)
mysqli_connect_errno should be a function: mysqli_connect_errno()
mysqi_connect_error() instead of mysqli_connect_error() (note the l in mysqli)
The reason you're getting a 500 error is that you do not have debugging enabled. Please add the following to the very top of your script:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
That should prevent a not-so-useful 500 error from appearing, and should instead show the actual reason for any other errors.
There might be a problem here:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
If the query fails, $result will be false and you will get an error on the mysqli_num_rows() call. You should add a check between there:
$result = mysqli_query($conn, $sql);
if (!$result) {
die('Query failed because: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
The name of your database table in your select statement has a space in it. If that is intended try:
$sql = 'SELECT Name FROM `Employee List`';
i think you left blank space in your query.
$sql = 'SELECT Name FROM Employee List';
change to
$sql = "SELECT `Name` FROM `EmployeeList`";

PHP variables not printing to HTML webpage

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();
?>

Issues with PHP connection script to MSSQL database

Good morning,
I am quite new to php and I am trying to create a connection to a MSSQL server, I've been able to do it through MYSQL php connection but what I thought would be a simply change to MSSQL is proving to be much harder than expected.
The below code is basically what I am using after much googleing and search in this website this is what i've come up with:
<?php
$Server = "127.0.0.1";
$User = "BOB123";
$Pass = "BOBPASS";
$DB = "BOBDB";
//connection to the database
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbconn)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT CustomerName from tblCustomer ";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<br>" . $row["name"];
}
//close the connection
mssql_close($dbconn);
?>
As you can see the above script is very basic and there are very similar ones knocking around on the web could anyone help in connecting to the server this script doesn't seem to want to connect. I've changed the log on details as you'd probably know.
Thanks
Kris
You have a typo on:
$dbconn = mssql_connect($Server, $User, $Pass);
Should be:
$dbconn = mysql_connect($Server, $User, $Pass);
You're typing mysql wrong on each mysql_ function you create, change all mssql_ to mysql_
Note:
You shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi.
#Daniel Gelling Doesn't look like a typo, looks like he is trying to connect to Microsoft SQL Server using mssql. You are correct about the API being outdated however.

mysql vs mysqli config file and queries

I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.

Categories