Delete row from MySQL not working - php

I'm trying to delete a row from a table in MySQL using the PHP code below. The return value from mysql_affected_rows() is 1. There are no errors. However, the row still exits in MySQL. Not sure what I'm doing wrong. Any thoughts?
$db = array('host'=>'127.0.0.1',
'user'=>'root',
'pass'=>'',
'name'=>'testdb');
// CONNECT TO THE MYSQL SERVER
$connection = mysql_connect($db['host'], $db['user'], $db['pass']);
if(!$connection){
// HANDLE ERROR HERE
die('Unable to connect to MySql server : '.mysql_error($connection));
}
// SELECT THE DATABASE SCHEMA
if(!mysql_select_db($db['name'],$connection)){
// HANDLE ERRORS HERE
die('Unable to connect to database : '.mysql_error($connection));
}
$result = mysql_query("delete from photos where id=".$photo_id, $connection);
echo mysql_affected_rows($connection);
UPDATE
I added the following code to the end and that solved the issue -
mysql_query("commit", $connection);
Thanks for the comments!

Applied to innodb tables as in your case.
mysql_query("BEGIN", $connection);
// delete code
mysql_query("COMMIT", $connection);

What I typically do in this cases is to enable the general_log (set global general_log_file=general.log; and set global general_log=1;) and look what arrives in there.
Then it often becomes already obvious what is the problem.
If it is not clear yet what is going on you can run these queries on the mysql console...

Related

Table does not exist, but it EXISTS

So I'm starting to learn how to use PHP to access MYSQL databases and after successfully connecting to the database. I want to select data from it. However I get the issue that the table doesn't exist. Yet, it exists when I check it in my phpmyadmin. I've checked spelling, capitalization, etc.. and nothing works. I've tried it with multiple databases and I get the same error. So I'm really confused as to whats going on because from the looks of it, there is NOTHING wrong with the code. I've tried running the SQL query in phpmyadmin just to verify that the query works.. and it does. I just get the error "Table 'test.blog_table' doesn't exist" with the code below
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_in_use = "test";
$conn = new mysqli($host, $user, $password, $database_in_use);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
echo $conn->host_info . "<br>";
$sql = "SELECT * FROM blog_table";
$result = $conn->query($sql);
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
So I'm just completely lost and have no idea whats going on with it.
Solved! I connected to the wrong database, which is why the tables were there, but weren't showing up. Since I was connecting to a different database and the one I created tables in didn't have the default port.
Probably you are missing the mysqli and the mysqlnd PHP extensions.
Also, I recommend you to use \PDO object to fetch queries to your DB instead of the mysqli driver, if you do it, you will be free to change in the future to a PostgreSQL DB for example anytime just changing the DSN in the constructor (you need for that the PDO and the pdo_whatever_db_driver (e-g.: pdo_mysql) extensions.

PHP mySQL Update doesn't work

I currently have a very big problem with PHP and mySQL. I moved a System I coded to a new Server. And while everything worked fine on the old Server, I had some problems on the new Server. Especially with mySQL. While I solved nearly all of them, I have one which I can't seem to get a hold on. And after 2 hours of trying i searched on the Internet for another two hours and updated my Syntax several times. But nothing seems to work. So now I'm here. I get a Connection to the database without a problem, but I can't update the values. I hope you can help me.
//Connect to mySQL Database
$verbindung = mysql_connect($server, $username, $passwort);
if (!$verbindung) {
echo "Couldn't connect: " . mysql_error();
}
$name=$_POST['fuehrer'];
$ident=$_POST['id'];
//Debugging
echo $name;
echo $ident;
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';";
if (!mysql_query($verbindung, $sql_befehl_0)){
echo "Couldn't write to database";
}
//Close connection
mysql_close ( $verbindung );
What version of php use? Because in the newest versions of php the mysql functions are deprecated/removed, use instead mysqli.
Try to echo a mysqli_error at the end of the code, also mysql_error if your version of php accepts mysql functions.
If not version of php is the problem check this:
Wrong things what i see in your code..:
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';"; // wrong
should be:
$sql_befehl_0="UPDATE `olgatermine` SET `fuehrer` = '".$name."' WHERE ID = '".$ident."';";
You need to run mysql_select_db('dbname') below line you do the mysql connection.
You can set at the first line of file:
ini_set('display_errors',1);
error_reporting(E_ALL);
to show all errors.

MySQL I can not write data into the database

Hello guys i have problem with inserting data in mysql database.I accepted a project that my friend worked.
I make simple php test file and try to insert in table _content_city. query is successfully executed bu no records in database column when i check in phpmyadmin.
$handler = mysql_connect($server, $user, $pass);
$database = mysql_select_db($dbname);
if(!$handler) :
die("Faild connect to MySQL :" . mysql_error());
endif;
if(!$database) :
die("DB with name ". $dbname . " no exists " . mysql_error());
endif;
mysql_query("INSERT INTO _content_grad (wishlist) VALUES('BlaBlaBla') ") or die(mysql_error());
printf ("Inserterd records: %d\n", mysql_affected_rows());
When i execute this code in browser i have message Inserterd records: 1
But when i check in phpmyadmin that data no exist in column. I dont know whay.
You guys can see image and u will see column wishlist is empty.
http://img710.imageshack.us/img710/1852/5hfw.png
I check foreign_keys and remove all foreign_keys and again dont work.
Like test i make new database with name new_test_base and make table albums and column title and like test i execute my php code and all data is successfully inserted when i check in phpmyadmin. So problem is only in that database, i have full access and privilegies i use root (ALL)
Any solution to fix this. Thanks
The MySQL_* range of functions have been depreciated and are no longer reccomened for use. Use the MySQLi_* range of functions instead.
In your code, put the following line echo mysql_errno($handler) and it should display the latest error retuned by MySQL, a MySQLi version of this function is also available.

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

Can I use MySql Create Select on two different servers with PHP?

I am trying to use PHP and MySQL's Create Table Select between two different MySQL servers. I am not sure this can be done like this with SQL. I get no errors but I get nothing done either:
<?php
$dbname = 'cms';
$dbmaster = 'cmsms';
$db1 = mysql_connect('localhost', 'root', 'secret');
if (!$db1) {
echo 'Could not connect to mysql';
exit;
}
$db2 = mysql_connect('server2', 'root', 'secret');
if (!$db2) {
echo 'Could not connect to mysql';
exit;
}
mysql_select_db("$dbname", $db1) or die ("Unable to select database");
mysql_select_db("$dbmaster", $db2) or die ("Unable to select database");
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql, $db1);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
$sql = "DROP TABLE `$row[0]`";
mysql_query($sql, $db1);
echo "Table rows: {$row[0]} Deleted <br/>";
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
mysql_query($sql, $db1);
echo "Table: {$row[0]} created <br/>";
}
echo "<br/>done...";
mysql_free_result($result);
?>
That line:
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
just doesn't work. the $db2 doesn't make it go to the other server and select.
From doing some reading on SO I found someone similar and someone said it could not be done and to look at federated tables, which will not work for me.
If this cannot be done above does anyone know a way to do what I am doing? I am dropping the tables on the copy and re-creating them based on the table in the master. Then I am selecting the data in the master to put in the re-created tables. Thank you
Update:
Just so I can be clear. The code works if everything were on the same server and I only had one database connection. It is because of the create table select that I have problems, I believe. This SQL needs to use two servers at the same time. The create table is for one database that just dropped it's tables but the select is selecting from the database of the second connection - two connections in the same SQL statement.
Yes, on your PHP script you can perform all queries you want on all different servers you have access and permission to.
You don't specify your database on the $sql though. You specify it when you run the mysql_query function.
So, your code:
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql, $db1);
Is wrong. It should only be:
$sql = "SHOW TABLES";
$result = mysql_query($sql, $db1);
By using $db1 on the second parameter of mysql_query you are already specifying that you want to show tables from that database only.
Following the same reasoning on the other sentences, you should be able to get results you want.
You won't be able to do this:
$sql = "CREATE TABLE $row[0] SELECT * FROM $db2.$dbmaster.$row[0] ";
If you want to insert rows from $db2 into newly created tables into $db1, you need to:
Run a query on $db2 to get results
Create table on $db1
Iterate $db2 results
Insert records on new table on $db1
There is no magic way of doing this in only one sentence.
You're on the right track but missing an important point. Your PHP code has opened a connection to db1 and db2 but that doesn't mean that the db1 server knows about the db2 server. Therefore you can't pass db1 a query with db2 in it and expect it to get rows from it. Your PHP script has to act as an intermediary.
You need to issue a select statement to select rows from db1's table, then loop over the results issuing insert statements for db2. Of course you do this after you issue a create table statement to create the blank table. I'm also assuming you're trying the 'create table select from' trick because you don't know how to issue the create table to copy the layout of the table in db1. Have you seen this?
http://dev.mysql.com/doc/refman/5.0/en/show-create-table.html
remove the $db2 database connection from your query
If you want to run SQL on $db1 use this
mysql_query($sql, $db1);
If you want to run SQL on $db2 use this
mysql_query($sql, $db2);
I don't think this is the best database design Johnny, depends of course on what you're trying to achieve. If you simply want to store data on both servers for redundancy, you should go with MySQL Replication. If you're separating data for high availability purposes, then consider data sharding, partitioning and definitely take a look at MySQL Proxy.
These will let you do all the work outside your application, so you wouldn't have to alter your application in case your sharding/partitioning/backup/redundancy scheme changes. Such tools make this completely invisible to your application.
Sorry if this is off-topic.
There are a few choices you have in regards to setting this up.
1) Implement mysql asynchronous replication. This would do the same thing you are trying to do in PHP but would be much more efficient.
Mysql Documentation: Replication
2) Fix your script to stream data from master server to backup server.
This would be done by creating the table and then loading the result row by row into the backup server's table.

Categories