I have the following mysql table:
CREATE TABLE IF NOT EXISTS `spieler` (
`spielerID` int(11) NOT NULL,
`name` varchar(50) COLLATE latin1_german1_ci NOT NULL,
`vorname` varchar(50) COLLATE latin1_german1_ci NOT NULL,
`jahrgang` varchar(10) COLLATE latin1_german1_ci NOT NULL,
`bemerkung` varchar(300) COLLATE latin1_german1_ci NOT NULL,
`mannschaft` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci;
ALTER TABLE `spieler`
ADD PRIMARY KEY (`spielerID`),
ADD KEY `mannschaft` (`mannschaft`);
ALTER TABLE `spieler`
MODIFY `spielerID` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `spieler`
ADD CONSTRAINT `spieler_ibfk_1` FOREIGN KEY (`mannschaft`) REFERENCES `mannschaft` (`mannschaftID`);
and the php code to get the data out of the db:
$id = $_GET['id'];
//echo "ID ist".$id;
$sql = "SELECT * FROM spieler WHERE mannschaft = '.$id.'";
if (!$result = $db->query($sql)) {
die("Fehler: ['.$db->error.']");
}
echo "<table class='table table-striped'>";
echo "<tr><td><b>ID</b></td><td><b>Name</b></td><td><b>Vorname</b></td><td><b>Jahrgang</b></td><td><b>Bemerkung</b></td><td><b>Bearbeiten</b></td><td><b>Löschen</b></td></tr>";
while ($row = $result->fetch_assoc()) {
echo '<tr><td>'.$row['spielerID'] . '</td><td>'.$row['name'].'</td><td>'.$row['vorname'].'</td><td>'.$row['jahrgang'].'</td><td>'.$row['bemerkung'].'</td><td><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></td><td><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></td></tr>';
}
echo "</table>";
The above code works perfectly fine if there are only two entries in the table. But if there are more then two entries, the table is not getting displayed. It only shows the tablehead.
What am I doing wrong? Or am i missing something?
Change your sql query like give below.
$sql = "SELECT * FROM spieler WHERE mannschaft = '".$id."'";
Related
When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.
This is the table for upload
CREATE TABLE `upload` (
`id` int(10) unsigned NOT NULL auto_increment,
`deskripsi` text,
`filetype` varchar(200) default NULL,
`filedata` longblob,
`filename` varchar(200) default NULL,
`filesize` bigint(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=49 ;
This is the table for article
CREATE TABLE `info` (
`id_info` int(10) NOT NULL auto_increment,
`judul_info` varchar(50) collate latin1_general_ci NOT NULL,
`konten` varchar(50000) collate latin1_general_ci NOT NULL,
`diubah_oleh` varchar(20) collate latin1_general_ci NOT NULL,
`id_kategori` int(10) NOT NULL,
`tgl_buat` timestamp NOT NULL default '0000-00-00 00:00:00',
`tgl_ubah` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`dibuat_oleh` varchar(20) collate latin1_general_ci NOT NULL,
`id` int(10) NOT NULL,
PRIMARY KEY (`id_info`),
KEY `id_kategori` (`id_kategori`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=5 ;
This is my source code for index.php
<?php
include "config.php";
$query= "SELECT upload.filetype, upload.filename, upload.filedata,
info.judul_info, info.konten, info.diubah_oleh, info.id_info, info.tgl_buat,
info.tgl_ubah, info.dibuat_oleh, info.id
FROM info
JOIN
upload
ON info.id = upload.id WHERE id_info='4'";
$runquery = mysql_query($query);
while($result = mysql_fetch_array($runquery))
{
$id = $result['id'];
echo "<img src=get_image.php?id=$id>";
?>
<div class="caption">
<?php
$id_info = $result['id_info'];
$judul = $result['judul_info'];
$konten = $result['konten'];
echo "<h3>$judul</h3>";
echo "<p>".substr($result['konten'], 0, 100)."...</p>";
echo "<a href=detail_info.php?page_detil=$id_info>Selengkapnya</a><br><br>";
}
?>
And, this is my source code for get_image.php
<?php
include "config.php":
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM upload WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['filedata'];
header("Content-type: image/jpeg");
echo $image;
?>
I want the images to shown with the article, i can show the title and the content of the article but the images won't showed up. anybody can help me?
First: Please avoid to pass user input to a query directly! You should also switch to mysqli or PDO: http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use--net-24059
To solve your problem, you should quote your image href:
echo "<img src='get_image.php?id=$id'>";
If this does not help, open your get_image.php in your browser. Does the image show up? If not, check your query's result (just comment the header line to see the output).
I'm currently making a timesheet website based on PHP & mySQL, I encountered a problem where I would be pulling multiple data in tables with multiple condition, here are some of the codes:
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$uid = $_SESSION['user_id'];
$data_query = "SELECT users.user_name, jobs.job_code, jobs.job_desc, jobs.job_client, jobs.job_year, jobs.job_month, jobs.job_category, job_taker.job_hours ".
"FROM jobs,job_taker,users ".
"WHERE 'login.jobs.job_id' = 'login.job_taker.job_id' AND 'login.users.user_id' = ('.$uid.')".
"ORDER BY 'login.jobs.job_id' DESC";
$data_result = mysqli_query($db_connection,$data_query) or die(mysql_error());
Here are where I would be showing the result:
<?php
while($info = mysqli_fetch_array($data_result)) {
?>
<tr>
<td> <input type="checkbox" name="<?php echo $info['job_code']?>" id="<?php echo $info['job_code']?>" value="<?php echo $info['job_code']?>" /></td>
<td><?php echo $info['user_name'] ?></td>
<td><?php echo $info['job_code'] ?> </td>
<td><?php echo $info['job_client'] ?> </td>
<td><?php echo $info['job_year'] ?> </td>
<td><?php echo $info['job_month']?> </td>
<td><?php echo $info['job_date']?> </td>
<td><?php echo $info['job_category']?> </td>
</tr>
<?php } ?>
And here are the SQL dump from my database:
CREATE TABLE IF NOT EXISTS `jobs` (
`job_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`job_code` varchar(32) NOT NULL,
`job_desc` varchar(500) NOT NULL,
`job_client` varchar(500) NOT NULL,
`job_year` int(11) NOT NULL,
`job_month` int(11) NOT NULL,
`job_date` int(11) NOT NULL,
`job_category` varchar(25) NOT NULL,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `job_taker` (
`user_id` bigint(20) unsigned NOT NULL,
`job_id` int(11) unsigned NOT NULL,
`job_hours` int(11) unsigned NOT NULL,
PRIMARY KEY (`user_id`,`job_id`),
KEY `user_id` (`user_id`),
KEY `user_id_2` (`user_id`),
KEY `job_id` (`job_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `users` (
`user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',
`user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name',
`user_position` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`user_status` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`user_password_hash` char(60) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format',
`user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email',
`user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
`user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
`user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
`user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data' AUTO_INCREMENT=8 ;
ALTER TABLE `job_taker`
ADD CONSTRAINT `job_taker_ibfk_2` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `job_taker_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
My problem is that when I tried to open the page that shows it, it didn't show any data at all. It didn't gave any SQL syntax error, just plain blank data page.
Here are the results when i tried to echo $data_result
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\seclog\views\user_edit_job.php on line 11
Is there any way to fix this?
Thank you to anyone that try to help or read this!
Make a condition for job_taker and users like
job_taker.user_id=users.user_id
Query,
$data_query ="SELECT users.user_name, jobs.job_code, jobs.job_desc,
jobs.job_client, jobs.job_year, jobs.job_month, jobs.job_category,
job_taker.job_hours FROM jobs,job_taker,users WHERE
jobs.job_id = job_taker.job_id AND users.user_id ='$uid' AND
job_taker.user_id=users.user_id ORDER BY 'login.jobs.job_id' DESC";
This will not get any result as condition always false...
'login.jobs.job_id' = 'login.job_taker.job_id'
And so will this...
'login.users.user_id'='$uid'
You both left and right are strings. If you want to indicate database field on the left, then you should be using ( ` ) instead of ( ' ).
Example...
`login`.`jobs`.`job_id`
Do the same if item on the right is also a database field.
I use the above as it is safer than login.jobs.job_id, because one of the field or table names could be a reserved word and that could cause problems if u do not use ( ` )
If it is value then use ( ' ).
Hello you are getting object as result in $data_result variable.
So you can not directly echo it.
Try this
print_r( $data_result );
I restarted the MySQL service and I attempted to use my PHP programs delete function to delete an existing row but I'm finding although the delete queries were counted the row was not deleted. I tried applying on delete cascade to the foreign key of the child table but that did not seem to have an effect. I'm wondering why the delete would be doing nothing.
CREATE TABLE `customers` (
`idcustomers` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`lastname` varchar(45) DEFAULT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`cell` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idcustomers`),
UNIQUE KEY `idcustomers_UNIQUE` (`idcustomers`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=latin1
CREATE TABLE `events` (
`idevents` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`allday` varchar(50) DEFAULT NULL,
`url` varchar(1000) DEFAULT NULL,
`customerid` int(11) NOT NULL,
`memo` longtext,
`dispatchstatus` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idevents`),
KEY `FK_events` (`customerid`),
CONSTRAINT `FK_events` FOREIGN KEY (`customerid`) REFERENCES `customers` (`idcustomers`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
Com_delete 2
The PHP looks like this:
<?php
session_start();
date_default_timezone_set("America/Los_Angeles");
if($_SESSION['loggedin'] != TRUE)
{
header("Location: index.php");
}
require_once('../php.securelogin/include.securelogin.php');
$mysqli = new mysqli($ad_host, $ad_user, $ad_password, "samedaycrm");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$customerid = $_SESSION['customer_id'];
$tSQL = "delete from events where customerid = \"$customerid\"";
$result = $mysqli->query($tSQL);
$tSQL = "delete from customers where idcustomers = \"$customerid\"";
$result = $mysqli->query($tSQL);
echo $mysqli->error;
?>
Assuming that the customerid and idcustomers columns are both numeric it should be fine. You should not need to quote the variables in those queries btw, then you wouldnt need to escape them. You may try:
$tSQL = "delete from events where customerid = $customerid";
but it should not be any different than what you used already. Of course if you are not sure of the type of the column you can use:
$tSQL = "delete from events where customerid = '".$customerid."'";
or you can get away with:
$tSQL = "delete from events where customerid = '$customerid'";
but I have always hated that for some reason.
if all of that fails troubleshoot by spitting out the $customerid (or even the whole $tSQL) variable and then trying the query manually in phpmyadmin or toad or whatever db client you use, and see what it tells you. If it just says 0 rows affected, then run it like a select instead. Tailor to fit.
I am developing a cooking recipe-website and i want to create a recipe finder based on the used incredients.
My current finder only works with 3 ingredients right.
The Finder should return the right recipe(s) based on the used incredients (should work with 1-n*)
My Tables:
CREATE TABLE IF NOT EXISTS `INGREDIENTS` (
`ingredients_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `INGREDIENTS_POS` (
`ingredients_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`ingredients_id` int(11) NOT NULL,
`ingredients_unit` varchar(20) NOT NULL,
PRIMARY KEY (`ingredients_pos_id`),
KEY `ingredients_detail_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `RECIPES` (
`recipes_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_bin NOT NULL,
`text` varchar(2000) COLLATE utf8_bin NOT NULL,
`count_persons` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`accepted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`recipes_id`),
KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;
CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
`recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`recipes_id` int(11) NOT NULL,
`ingredients_id` int(11) NOT NULL,
`ingredients_value` int(11) NOT NULL,
PRIMARY KEY (`recipes_pos_id`),
KEY `recipe_pos_rec_id` (`recipes_id`),
KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
My buggy Solution (doesn't support count from 1-n):
<?php
include 'db_connect.php';
$q = urldecode(mysql_real_escape_string($_GET['q']));
$parameter = explode ('$',$q);
$var = 0;
//print_r($parameter);
foreach($parameter as $ing)
{
//echo $ing;
$sql = "SELECT ingredients_id FROM INGREDIENTS WHERE name='".$ing."'";
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
$row = mysql_fetch_array($result);
$arr_id[$var] = $row['ingredients_id'];
$var++;
}
//print_r($arr_id);
$sql = "SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id ";
foreach($arr_id as $id)
{
$sql .= "AND rp.ingredients_id =".$id . " ";
}
//echo $sql;
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
mysql_close($db);
$rec;
while($row = mysql_fetch_array($result))
{
//echo "test";
$_GET['id'] = $row['recipes_id'];
$rec= include('get_recipe_byID.php');
}
//print_r(mysql_fetch_array($result));
if (count($arr_id) == 0)
{
echo '{"Data":null,"Message":null,"Code":404}';
die();
}
?>
I need a better solution for that chase.
Maybe SQL itself will help me to find the right recipes
thx
That query helped me a lot:
select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2