I'm a beginner here I need to learn the basic in converting from mysql to mysqli. I want to start in configuration first. I have used this connect.php and it's working now I wanted to switch to undeprecated mysqli. Please advise me how to modify this script.
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname = "student";
$link_id = mysql_connect($host, $dbusername, $dbpassword);
if(!$link_id){
die(mysql_error("Can`t Connect To database"));
}
else{
$db = mysql_select_db($dbname, $link_id);
}
if(!$db){
die(mysql_error("Can`t select database"));
}
return;
?>
According to my comment....
you could do it that way
$host = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname = "student";
$link = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link));
$query = "SELECT knowhow FROM google WHERE myknowhow='leaks'";
$knowhow = mysqli_query($link, $query);
this is just the simplest way you can do it.
But you should use it like this (OOP)
$db = new mysqli($host,$dbusername,$dbpassword,$dbname);
$knowhow = $db->query("SELECT knowhow FROM google WHERE myknowhow='leaks'");
According to your comment:
You dont need the IF/ELSE statements anymore. All errors are catched with
die("Error " . mysqli_error($link));
In the oop, errors are catched in
... new mysqli($host,$dbusername,$dbpassword,$dbname);
EDIT
Since you where blocked asking new questions ill just update this answere:
$link = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link));
$query = "SELECT * FROM student_information where student_id='{$_SESSION['user_id']}'";
$knowhow = mysqli_query($link, $query);
$data = mysqli_fetch_array($result);
$numRows = mysqli_num_rows($result);
$i = 0;
while($i < $numRows){
echo $data[$i++] . "<br />";
}
// I would not use a while in this case. I would prefere a foreach
// just to prevent from using a endless loop and 1 row less code :)
foreach($data as $d){
echo $d . "<br />";
}
Please use MySqli as a Class like $db = new Mysqli();
Related
<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.
I would need some help with showing data that I have on my database but I can't seen to be able to.`
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$connect = mysqli_connect($servername, $username, $password, $dbname) or die ("connection failed");
//Query
$query = "SELECT * FROM 'Students'";
mysqli_master_query($dbname, $query) or die ("Error while Query");
$result = mysqli_master_query($dbname, $query);
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
echo "<p>".$row['Name']."</p>";
};
mysql_close($connect);
?>`
I am pretty new to this so I could have missed something simple. Any help appreciated.
Below is a sample code of the normal procedure to connect to a database and to select data from it. Please follow this type of coding since MySQL is now deprecated and MySQLi is used.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp
I am trying to get a question with answers out of my database. I just want to get one thing out of the database and not with a row. I thought this would work but it puts out this: Resource id #4 can someone explains what I am missing.
Thanks :)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysql_query($sql);
echo $test;
?>
As said at least 10000 times everywhere in internet, never use MySQL_ ! (If your are trying to learn something new by using tutorials over internet, don't use old ones)
I recommend to use PDO which is modern API in PHP and a lot more secure when using it correctly with prepared statement ! But you can also use MYSQLI which is more similar to the MYSQL !
You have to export your data from return array :
Using PDO :
$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
$query = $db -> prepare ("SELECT * FROM vraag1");
$query -> execute (array ());
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
echo $id = $row["id"];
echo $vraag = $row["vraag "];
echo $AntwA = $row["AntwA "];
echo $AntwB = $row["AntwB "];
echo $AntwC = $row["AntwC "];
echo $AntwD = $row["AntwD "];
}
Using MYSQLI :
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM vraag1";
$rows = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($rows))
{
echo $row["id"];
echo $row["vraag"];
echo $row["AntwA"];
echo $row["AntwB"];
echo $row["AntwC"];
echo $row["AntwD"];
}
First of all the mysql function you are using is depreciated and no longer supported. you should use mysqli or pdo instead with prepared statements.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "lotto";
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1";
$test = mysqli_query($conn, $sql);
if (mysqli_num_rows($test) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($test)) {
echo "ID : ".$row['id']."<br>";
echo "vraag :".$row['vraag']."<br>";
echo "AntwA :".$row['AntwA']."<br>";
echo "AntwB :".$row['AntwB']."<br>";
echo "AntwC :".$row['AntwC']."<br>";
echo "AntwD :".$row['AntwD']."<br>";
}
} else {
echo "no results found";
}
mysqli_close($conn);
?>
For select function mysql_query() returns a resource on success, or FALSE on error.
so your assignment statement
$test = mysql_query($sql);
assign the resource to $test.
if you want the data inside the resource you can do
while($row= mysql_fetch_assoc($test)):
print_r($row);
endwhile;
also you can access the $row['column_name']
If you want to return only one row you can do this limit in query
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1 limit 1';
You need to add something like the following:
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['vraag'];
echo $row['AntwA'];
echo $row['AntwB'];
echo $row['AntwC'];
echo $row['AntwD'];
}
use mysqli instead of mysql
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysqli_query($sql);
echo $test;
?>
I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help.
I am trying to calculate the sum of 2 columns in my database using PDO.
here is my code
<?php
$host = "localhost";
$db_name = "dbname";
$username = "root";
$password = "root";
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
// show error
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$row = $query->fetch(PDO::FETCH_ASSOC);
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill/$total_miles;
//display the answer
echo $myanswer
?>
I have also checked my database table and both columns are varchar(32)
the error I am getting is Call to a member function fetch() on a non-object
I have searched into this but not sure what's the issue with the above code
Thank You in advance
Try this code :-
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill / $total_miles;
//display the answer
echo $myanswer;
die;
}
} else {
echo "0 results";
}
$conn->close();
?>
I am trying to print all the rows in my database say 'student'. I am trying with many of codes with while loops and even examples from w3school. But, it's not working. Here's a simple code of php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect to MySql'.mysql_error());
}
mysql_select_db("StudDatabase") or die(mysql_error());
$sql = "SELECT * FROM Student";
mysql_query($sql);
mysql_close($conn);
?>
I am working in wamp server 2.2
Your code don't print the result of the query.
Try to add this code:
$results = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
But you should consider using PDO, mylsql is deprecated : http://php.net/manual/en/pdo.connections.php
$database = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($database->query('SELECT * FROM `Student`') as $row) {
print_r($row);
}