Trying to convert old mysql code to mysqli - php

I'm having to convert my inspection app to MySQLi but have been having many issues doing so since Amazon EC2 updated their MySQL
With not knowing much about php/mysql to begin with, I'm at a loss. Most of my searches have been way beyond what I understand.
This is what the file used to look like.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysql_query($query);
$num = mysql_num_rows ($result);
$username = mysql_result($result,$i,"username");
$oldurl = mysql_result($result,$i,"oldurl");
$homedata = mysql_result($result,$i,"homedata");
$clientemail = mysql_result($result,$i,"clientemail");
$general_info = mysql_result($result,$i,"general_info");
$company_name = mysql_result($result,$i,"company_name");
$company_hours = mysql_result($result,$i,"company_hours");
$company_phone = mysql_result($result,$i,"company_phone");
$company_support_email = mysql_result($result,$i,"company_support_email");
$beyondscope = mysql_result($result,$i,"beyondscope");
mysql_close();
?>
This is what I have so far. One error I'm getting line 17 has unexpected ',' (comma), even that every line has the same setup.
Thanks in advance for any help with this.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
$num = mysqli_num_rows($result);
$username = mysqli_fetch_array($result,$i,"username");
$oldurl = mysqli_fetch_array($result,$i,"oldurl");
$homedata = mysqli_fetch_array($result,$i,"homedata");
$clientemail = mysqli_fetch_array($result,$i,"clientemail");
$general_info = mysqli_fetch_array($result,$i,"general_info");
$company_name = mysqli_fetch_array($result,$i,"company_name");
$company_hours = mysqli_fetch_array($result,$i,"company_hours");
$company_phone = mysqli_fetch_array($result,$i,"company_phone");
$company_support_email = ($result,$i, "company_support_email");
$beyondscope = mysqli_fetch_array($result,$i,"beyondscope");
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
?>
UPDATE: To add connect.php
<?php
$hostname='.rds.amazonaws.com';
$user='username';
$pass='password';
$dbase='dbasename';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect("$hostname" , "$user" , "$pass"))
or die ("Can't connect to MySQL");
$db = ((bool)mysqli_query( $connection, "USE " . $dbase)) or die ("Can't select database.");
?>

I've taken the liberty of rebuilding a bit on how you fetch your values, this should be a bit more easier to read and (in my opinion) a better structure. Also, you can specify the database in your connection, like this (just makes for easier reading, up to you really).
$connection = mysqli_connect($hostname, $user, $pass, $dbase);
if (!$connection) {
echo "An error occurred connecting to the database.";
exit;
}
Below is how your query could look. This will loop through all the results, and put them into the variables, only if we actually have a result.
<?php
include "connect.php"; // Connect to RDS
$query = "SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
if (!$result = mysqli_query($connection, $query)) {
// An error occured, do something
// This means no results could be fetched
}
$num = mysqli_num_rows($result);
if (!$result) { // This means that we only fetch if we have a result
while($row = mysqli_fetch_assoc($result)) {
// Fetching all the rows
$username = $row['username'];
$oldurl = $row['oldurl'];
$homedata = $row['homedata '];
$clientemail = $row['clientemail'];
$general_info = $row['general_info'];
$company_name = $row['company_name'];
$company_hours = $row['company_hours'];
$company_phone = $row['company_phone'];
$company_support_email = $row['company_support_email'];
$beyondscope = $row['beyondscope'];
}
}
?>

JFYI.
There is absolutely no point in converting your inspection app to MySQLi the way it offered in the other answer.
The only point in such a conversion is to make your queries safe while with such a direct conversion it remained congenially vulnerable. So, you might saved yourself a lot of trouble by leaving this code alone, with exactly the same outcome.
Proper way is described in this answer, but you will have to find another volunteer to write a code for you.

Related

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`";

Connection is made to the database with php script but no values are returned

I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.

PHP MySQL unable to jump to row 0

I recently started studying webdevelopment and for the first project we have to make a very simple login and registration function. now I got somewhere but suddenly I started getting this error.
Unable to jump to row 0 on MySQL result index 4.
This is the code where I get the error.
$conn = mysql_connect($servername, $username, $password, $database) or die("!Server");
if(!$conn){
die("Connection error: " . mysql_error());
}else{
echo "connection made";
}
$select_db= mysql_select_db($database, $conn);
if(!$select_db){
die("Database selection failed:: " . mysql_error());
}else{
echo "database selected";
}
$login_user = $_GET['username'];
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
$result = mysql_query($select_password);
if(!$result){
die("Could not fetch the data " . mysql_error());
}
$password = mysql_result($result, 0);
echo $password;
I know there are other posts asking the same question but none of them where really helpful.
hope someone is able to help me.
Thanks for reading :)
It is possible that this row:
password = mysql_result($result, 0);
Cannot get rows when it does not match anything which is why you get the error.
Try instead:
if( $password = mysql_fetch_assoc($result) ) {
echo $password['password'];
} else {
echo 'no match';
}
See if that helps.
However, you really should move from mysql_* to PDO or mysqli.
I suggest to work with PDO, instead of mysql_... functions.
Not only because it's newer and object oriented but also because mysql... is deprecated.
So my answer is with PDO
From your code example I assume you have variables of servername, database, username & password. So to connect with PDO will look like this:
$con = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
Then you can take your $_GET parameter using filter_input, which is also more suggested. Simple assignment look like this:
$login_user = filter_input(INPUT_GET,'username');
and then to run & fetch query like this:
$result_query = $con->query("SELECT `password` FROM `members` WHERE `username` = '$login_user'");
$result = $result_query->fetch(PDO::FETCH_ASSOC);
Now $result is an associative array, so to get password just use:
echo $result['password'];
Thanks alot for the help :) out of these answers I got everything I needed and now I am also going to switch to PDO for the final release though I am gonna stay with MySQL for now since I have to turn it in by monday.
Thanks alot :)
Change this:
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
Into this:
$select_password = "SELECT password FROM members WHERE username = '$login_user'";

connecting to a database in mysql using php

Hey i'm new to php/mysql and i'm trying to execute a very simple php code that will display the contents of the table. I feel like the code is perfect, and i get no error messages, but for some reason it doesn't work. I know you guys hate debugging questions like this, but
if you could help i'd appreciate it. here's the php.
<?php
$conn=mysql_connect("localhost","demo","abc") or die(mysql_error());
mysql_select_db("practice");
$sql="SELECT*FROM contact";
$result=mysql_query($sql,$conn) or die(mysql_error());
while($row=mysql_fetch_assoc($result)){
foreach($row as $name => $value){
print "$name: $value <br>\n";
} //end foreach
print "<br /> \n";
} //end while
?>
You're using the old mysql library which is a no no
Get comfy with the Mysqli Extension for all your database access needs. I'll even refactor this a bit for you.
$conn = new Mysqli('localhost', 'demo', 'abc', 'practice');
$sql = "SELECT*FROM contact";
$results = $conn->query($sql);
while($row = $results->fetch_assoc())
{
var_dump($row);
}
edit: JimiDini posted a link that you should definitely read. http://phptherightway.com/
try this
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// or if you want to enable all PHP error reports, use this code below and comment out the one above
//error_reporting(-1);
$dbhost = 'localhost';// Server name (usually localhost)
$dbuser = 'user';// SQL Username (Make sure the user has access to the database!).
$dbpass = 'password';// SQL Password.
$dbase = 'db name';// SQL Database Name.
//connection to the database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die(mysql_error());
$sql = "SELECT * FROM `contact`";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
print_r($row);
}
but you should use mysqli in the future

Update existing mysql record using php

Trying to update existing records in phpMyAdmin, but the following code doesn't seem to be working.
<?php
$id = stripslashes($_POST['id']);
$title = stripslashes($_POST['title']);
$first = stripslashes($_POST['first']);
$surname = stripslashes($_POST['surname']);
$email = stripslashes($_POST['email']);
$promotion = stripslashes($_POST['promotion']);
$maths11 = stripslashes($_POST['maths11']);
$english11 = stripslashes($_POST['english11']);
$english13 = stripslashes($_POST['english13']);
$science13 = stripslashes($_POST['science13']);
$maths133 = stripslashes($_POST['maths133']);
$maths132 = stripslashes($_POST['maths132']);
$address = stripslashes($_POST['address']);
$address2 = stripslashes($_POST['address2']);
$town = stripslashes($_POST['town']);
$county = stripslashes($_POST['county']);
$code = stripslashes($_POST['code']);
$tel = stripslashes($_POST['tel']);
//database connection
$query="UPDATE Promotions SET address='$address', address2='$address2', town='$town', county='$county', postcode='$code', tel='$tel' WHERE id = '$id'";
mysql_query($query) or die(mysql_error());
include 'confirm.php';
include 'registerEmail.php';
?>
Any help? Thanks
Instead of rather useless die ('Error updating database'); handle your errors in more informative way
mysql_query($query) or trigger_error(mysql_error().' in '.$query);
and read what it says
Use mysql_error() like Col. Shrapnel showed.
But what troubles me ... Is that all the code for that page? Because you have //database connection but I don't see any database connection. Are you sure you are connecting to your database and included that connection in your file?
EDIT:
what does your query look like when you echo it? maybe the id is empty ... that way you can see what exactly is going to be send to the db
echo $query;

Categories