Valid MySQL Delete Query returning non-object - php

This one's a mystery to me and no one that I've read up on so far has had this issue, and I'm losing my mind here, so here goes. I'm trying to run this simple query from php on a mysql database with a user that has all required privileges (usually there is more than one entry in the ID array):
$sqlDelete = 'DELETE FROM wsa.customers WHERE `id` IN (18)';
$result = $conn->query($sqlDelete);
When I run this code from phpmyadmin and workbench this executes just fine, but not using php on the server (though it does handle updates and inserts without issue).
The $result is not a result object (though it should be) and I see no error or warnings at all...everything is as if nothing went badly though the user is obviously not deleted.
I'd just like to get input on where I should be looking as this is not a syntax issue....I've run out of ideas.
Thanks
UPDATE ON SCHEMA QUESTION:
CREATE TABLE `agreements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`creator_id` int(11) NOT NULL,
`term` tinyint(4) NOT NULL,
`contractDate` date NOT NULL,
PRIMARY KEY (`id`),
KEY `creatorid_idx` (`creator_id`),
CONSTRAINT `userid` FOREIGN KEY (`creator_id`) REFERENCES `master`.`login` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
CREATE TABLE `customers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`agreement_id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`plan` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `agreementid_idx` (`agreement_id`),
CONSTRAINT `agr_id` FOREIGN KEY (`agreement_id`) REFERENCES `agreements` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
UPDATE 2: Connnection Details:
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpass = 'yyy';
$conn;
$conn = new mysqli($dbhost, $dbuser, $dbpass, 'wsa');
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}

Sorry folks...in the end I was erroneously using if(!result) to test whether the query went through on a previous insert query to the one shown and it was causing the whole transaction to fail. My apologies. Thanks to #Darwin von Corax for pointing me in the right direction.

Related

$wpdb->insert is not respacting unique fields

I have been creating Wordpress plugin for a while. This is example of mysql table:
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT(11) NOT NULL AUTO_INCREMENT,
email VARCHAR(100) DEFAULT NULL,
telephone VARCHAR(15) DEFAULT NULL,
PRIMARY KEY(id),
UNIQUE (email, telephone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
";
Email should be unique, right? phpMyAdmin says it it.
This is wordpress code that inserts data into that table:
$err = $wpdb->insert($wpdb->prefix.$table_name, $data, $format);
var_dump($err);
It works, even more than it should. Assume email is m#m.com. First insert goes well. Second try fails because of duplicate entry as it should. var_dump is false.
BUT if I refresh wp page, third try with same email passes flawlessly, var_dump 1. Any repeated wp refresh opens db for duplicate entry.
Why? What am I doing wrong?
No, email is not UNIQUE here. Pair of email and telephone is UNIQUE in your table definition.
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT(11) NOT NULL AUTO_INCREMENT,
email VARCHAR(100) DEFAULT NULL,
telephone VARCHAR(15) DEFAULT NULL,
PRIMARY KEY(id),
UNIQUE (email),
UNIQUE (telephone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
";
Probably this is what you want.

MySQL and INSERT IGNORE

I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.

How do I log in and display information from two tables (MySQL)?

I'm new to MySQL and PHP so Im not sure how to approach this problem I'm having.
I have two tables right now.
CREATE TABLE `users` (
`userid` int(25) NOT NULL AUTO_INCREMENT,
`username` varchar(65) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`emailaddress` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
and
CREATE TABLE `images` (
`userid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`image` blob,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
so what I want to do is when a user signs in I want to be able to display an image that the user uploaded.
do I have to do something to the tables to make theme reference from each other?
help please!
Do you want just?...
select image from images
left join users on users.userid=images.userid
where username='whateverusername';
in the second table , the attribute userid should be a foreign key (i'd rather use Innodb to make sure that there is a foreign key constraint but it's up to u to use innodb or not)
so your table should look like this
CREATE TABLE images ( userid int(10) unsigned NOT NULL, name
varchar(50) DEFAULT NULL, image blob, foreign key userid
references users(userid) on delete cascade ) ENGINE=InnoDB
AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
once you do that, the table images will be linked to the table users which means that no record will be added to the table images unless the user id is already in the table users
if you wanna grab all the informations about that users including the image , you can perform a join between the two tables.
example with php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$user_id = 1;
$results = array();
> $results =mysql_query("select t1.userid,t1.username,t2.name,t2.image from users as t1 left join images as t2 on t1.userid=t2.userid where userid = $user_id",$con);
UPDATE:
make sure that the type of userid in both tables match

Create new SQL table on form submit IF TABLE NOT EXIST

I am new to php and SQL so this is probably an easy question but I could not find any good sources online.
I am trying to create a SQL table when someone submits a form and this is what I have so far
include("dbstufflive.php");
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
I will of course be doing other stuff with this table but I think I have most of that under control.
The problem is that this statement does not actually create my table :( The SQL statement works in phpadmin when I enter it as is and also there are no errors when the script runs. So it goes through all of this, and more, and seems to work but the table simply doesn't appear.
I can supply more code if needed but I don't want to paste more code here than is necessary.
Thanks in advance for any help from the community.
EDIT:
I was using wrong DBinfo...wow, I am not very bright.
Your SQL Statement looks fine - from the looks of it, you are missing your login credentials. An efficient way to do so:
// Add this line
require_once('config.php');
// Then change the variables below to pull your credentials from that file.
$cxn = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD)
or die("Couldn't connect to server");
$sql = "CREATE TABLE IF NOT EXISTS `$company` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(80) NOT NULL,
`contact` varchar(50) NOT NULL,
`email` varchar(80) NOT NULL,
`phone` varchar(13) NOT NULL,
... (long list of table data)
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ";
mysqli_query($cxn,$sql);
Then create a new file called config.php in same directory. Put your credentials:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'your_password');
define('DB_DATABASE', 'database_name');
?>
You should check the result of mysqli_query (as far as i know it returns false on failure). See mysqli documentation for details, where you can read, that "Create table doesn't return a resultset" but True/false on sucess/failure.
example:
if (!mysqli->query($cxn,$sql)) {
printf("Error: %s\n", mysqli_error($cxn));
}

Getting ID after inserting a record that has relation in Doctrine

I'm having a trouble with getting the id after inserting a new Record using PHP Doctrine Project.
In inserting a new record in a table with no parent table (no foreign key) no problem happens.
But when inserting a related record here comes the problem, that I get only the parent id which is useless in my case.
PHP code example:
$city = new City();
$city->name = "Baghdad";
$city->country_id = 6;
$city->save();
print_r($city->identifier());
exit;
The output is:
Array
(
[id] =>
[country_id] => 6
)
Why the ID is empty!, where the row was inserted successfully!.
I need this to do more insertion that based the city.id, like another areas that has this city as a parent.
Note using the $city->id causes this error:
Warning: Invalid argument supplied for foreach() in Doctrine/Record.php on line 1151
Database SQL Dump:
CREATE TABLE IF NOT EXISTS `country` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(64) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
CREATE TABLE IF NOT EXISTS `city` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(64) collate utf8_unicode_ci NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`,`country_id`),
KEY `fk_city_country` (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;
ALTER TABLE `city`
ADD CONSTRAINT `fk_city_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
BTW: I'm using the Doctrine::generateModelsFromDb() method to generate ORM model classes.
PS: using the Doctrine version 1.2.1, mysql:innodb 5.0.75-0ubuntu10.2, and php 5.2.6-3ubuntu4.5.
A co-worker discovered the solution.
It was because of this line of code:
PRIMARY KEY (`id`,`country_id`),
I used this:
PRIMARY KEY (`id`),
And it works correctly.
It's a MySQL issue I guess. It's not, it's bug in my tables design.
Does print_r($city->get('id')); hold more information?

Categories