I have this script that deletes a certain picture from the website. It's written with mysql functions so i wanted to update it to mysqli but doing so makes the script stop working. No die message from the script are shown no php errors and adding error_reporting(E_ALL); doesn't show any errors either.
Original script:
if(isset($_POST['F3Verwijderen']))
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysql_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("WEBSITE");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysql_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Updated to mysqli:
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("WEBSITE");
$result = mysqli_query($sql, $con);
while ($row = mysqli_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysqli_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysqli_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Edit:
"no php errors and adding error_reporting(E_ALL); doesn't show any errors either."
That's because it isn't a PHP issue, it's a MySQL issue.
Those are two different animals altogether.
As I said in commments, you need to switch these variables ($sql, $con) around ($con, $sql).
Then this:
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
Just use the 4th parameter instead of mysqli_select_db("WEBSITE"); where you didn't pass the connection variable to.
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS', 'WEBSITE');
The syntax is:
host
username
password (if any)
database
You also could have done mysqli_select_db($con, "WEBSITE");
Sidenote: In mysql_ (see footnotes), the connection comes last, unlike in mysqli_ which comes first.
Do the same for your UPDATE and pass the connection parameter first.
mysqli_query($con, "UPDATE...
Sidenote: To verify that the update truly was successful, use affected_rows()
http://php.net/manual/en/mysqli.affected-rows.php.
Another thing, mysqli_error() requires a connection to it mysqli_error($con) and check for errors for your queries.
I.e.:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.select-db.php
Sidenote:
You're using try() but no catch(). Either remove it, or consult the manual:
http://php.net/manual/en/language.exceptions.php
Example #4 pulled from the manual:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
Final notes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnotes: (MySQL and MySQLi comparison)
In regards to mysql_query():
mixed mysql_query ( string $query [, resource $link_identifier = NULL ]
http://php.net/manual/en/function.mysql-query.php
For mysqli_query():
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
http://php.net/manual/en/mysqli.query.php
Related
I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.
I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.
This is my source where I have this problem:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
What is wrong?
Thanks in advance!
You are mixing mysql and mysqli.
Try something like:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);
change to
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).
You don't even need the second $con parameter really.
Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.
I'd var_dump($con) before the mysql query to make sure it's a valid connection.
I am trying to use mysqli for the first time because i have some problems with multiple Query's in one php file. for start im just trying to retrieve data from the stored procedure and print it. but it looks like the code get's stuck somewhere it printed 'succesfull localhost' but it never get's to the code under it. The data never get printed neither the failed.
<?php
$link = mysqli_init();
if (!$link) {
die('mysqli_init failed');
}
if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!mysqli_real_connect($link, 'localhost', 'root', '', 'fabiola')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
//require 'header.php';
$resID = mysqli_real_escape_string($_REQUEST['resID']);
$materialen_id = mysqli_real_escape_string($_REQUEST['materialen_id']);
$aantal = mysqli_real_escape_string($_REQUEST['aantal']);
$effectief_gebruikt = mysqli_real_escape_string($_REQUEST['effectief_gebruikt']);
$opmerking = mysqli_real_escape_string($_REQUEST['opmerking']);
$datum_van = $_REQUEST['datum_van'];
$datum_tot = $_REQUEST['datum_tot'];
$sqm = "CALL aantal_besch_mat_van_tot($datum_van,$datum_tot,$materialen_id,$resID)";
//$result = $mysqli->query($sqm) or die('Query Failed!');
/* Select queries return a resultset */
if ($result = $mysqli->query($sqm)) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}else{
echo 'failed';
}
mysqli_close($link);
?>
Where is $mysqli set or initialized?
There should be something like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
but I can't see it.
btw it's weird that you're mixing the function calling convention 'mysqli_real_escape_string(...)' with the object-orientated functions '$mysqli->query(...)' I'm not sure it's safe to do both.
Also, you will save yourself a lot of heartache by using the MySQLi prepared statements rather than trying to make all your input safe by hand e.g.
$query = "CALL aantal_besch_mat_van_tot(?, ?, ?, ?);";
$statement = $mysqli->prepareStatement($query);
$statement->bind_param('iiii', $datum_van, $datum_tot, $materialen_id, $resID);
$statement->execute();
//get the results.
$statement->close();
$mysqli->close();
It's just so much easier, and more secure to use prepared statements (at the cost of a few percent of performance) that really you should almost always use them.
What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.