AND condition not working in MySQL Query - php

Please i need your help with my script. Whenever i include
AND maintable.semester_name = '$semester_name'
in the MySQL Query, it returns 0 for both values of semester_name, when actually
only one is supposed to have a value of 0 when echo $nums is processed. When i
remove
AND maintable.semester_name = '$semester_name'
the query gives normal results as i expect.
Thanks.
$query = "SELECT *
FROM maintable
WHERE maintable.matric_no = '$matric_no'
AND maintable.session = '$session'
AND maintable.semester_name = '$semester_name'
AND maintable.level = '$level'";
$result = mysql_query($query);
$nums = mysql_numrows($result);
echo $nums ;
TABLE STRUCTURE
COURSES
course_id int(100)
course_code varchar(100)
course_title varchar(100)
course_unit int(10)
MAINTABLE
maintable_id int(255)
matric_no int(10)
session varchar(10)
semester_name varchar(10)
course_code varchar(10)
level int(10)
score int(10)
grade varchar(4)
RESULT_UPLOAD
upload_id int(10)
session varchar(10)
semester_name varchar(10)
course_code varchar(10)
level varchar(10)
SEMESTER
semester_id int(10)
semester_name varchar(10)
STUDENT
matric_no int(10)
first_name varchar(100)
last_name varchar(100)
other_name varchar(100)
level int(10)
USERS
users_id int(10)
title varchar(20)
first_name varchar(20)
last_name varchar(20)
username varchar(20)
password varchar(100)
register_date datetime
tmp_name varchar(100)
type varchar(20)
name varchar(20)
size int(10)
YEAR
level_id int(10)
level int(10)

Your query is correct, but with bit of ambiguity. The following query is run as exactly you are doing, but with less words.
$query = "SELECT *
FROM maintable
WHERE matric_no = '$matric_no'
AND session = '$session'
AND semester_name = '$semester_name'
AND level = '$level'";
Now, about your problem, the only way this might be happening may be due to no record is matching the records in your database.
Try to get the query you are running with echo $query and run the query directly from phpmyadmin to see how many result set you will get.

The query is correct. I guess your conditions really don't match any rows in the table. Just check what values you have in the database and what your are passing into the conditions.

Try this query ...it works
$query = "SELECT *FROM maintable WHERE maintable.matric_no = '".$matric_no."'AND maintable.session = '".$session."' AND maintable.semester_name = '".$semester_name."' AND maintable.level = '".$level."' ";

Related

not able to create mysql table

i have a table tracker_item that looks like this
tracker_item
id heading trackerid
1 name 1
2 location 1
3 age 1
4 candidate 2
5 area 2
I wish to create different database table according to trackerid using the parameters that are below heading.
E.g acc to the above table tracker_item i want that 2 tables should get created
table1
id name location age
table 2
id candidate area
The code that i tried is
$sql="SELECT * FROM `tracker_item` where trackerid='".$trackerid."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
echo $sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
".
$row['heading']
." VARCHAR(30) NOT NULL,
resume VARCHAR(50)
)";
}
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
output for $sql1 that i got was
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, location VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, age VARCHAR(30) NOT NULL, resume VARCHAR(50) )
Instead of multiple tables i would like to get o/p of $sql1 look like the following so that a table can be created in database
CREATE TABLE item ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(50) )
Can anyone please tell how it can be done
You just need to modify your while loop and do the CREATE before the loop. You only want the loop to add columns via concatenation:
if(mysqli_num_rows($result)>0)
{
$sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, ";
while($row = mysqli_fetch_assoc($result))
{
$sql1 .= $row['heading']." VARCHAR(30) NOT NULL, ";
}
$sql1 .= "resume VARCHAR(50)) ";
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
Concatenate the entire query in this way and then execute the query.
Output:
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(30) NOT NULL, candidate VARCHAR(30) NOT NULL, area VARCHAR(30) NOT NULL, resume VARCHAR(50))
I hate when people say "I'm not that far along..." or "This site will not be public..." or "It's only for school, so security doesn't matter...". If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, "I'll add security later..." or "Security isn't important now..." or "Ignore the security risk...". If you don't have time to do it right the first time, when will you find the time to add it later?

select from 2 table and make ordering them

first, sorry for my English ...
what i want is to select from two SQL tables and then make them in a specific order , like in forums ...
i have two table, topic and users, i want to select from both of them a putt author info next to his topic
here is the SQL of Topic and users
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`author_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and the php code might look like this
<?php
$sql = mysql_query(' MySQL query ... ');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
is there any way to do it ??
As I understood, what you are looking for is the correct SQL statement to execute. The following simple solution will.
<?php
$sql = mysql_query('SELECT users.username, topics.message FROM `users` INNER JOIN topics ON topics.author_id = users.id');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
SELECT * FROM `users` INNER JOIN topics ON topics.author_id = users.id'

Get a record with maxid and condition in mysql in yii, but sometime it get second record?

my table:
CREATE TABLE IF NOT EXISTS `the_kho_chi_tiet_with_id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ngay_thang` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ma_phieu` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`id_san_pham` int(11) NOT NULL,
`id_kho` int(11) NOT NULL,
`khoi_luong_nhap` double NOT NULL,
`so_luong_nhap` int(11) NOT NULL,
`khoi_luong_xuat` double NOT NULL,
`so_luong_xuat` int(11) NOT NULL,
`khoi_luong_ton` double NOT NULL,
`so_luong_ton` int(11) NOT NULL,
`kho_du_tru` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
PHP code:
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
**Get a record with maxid and condition in mysql in yii, *but sometime it get second record* !?**
Please check with the below, hope it works!..if not please tell...
$id_kho=373;//sample value declaration
$id_san_pham=1;//sample value declaration
$select="select max(id) as id,so_luong_ton, khoi_luong_ton, kho_du_tru from
the_kho_chi_tiet_with_id where users_ref_id=".$id_kho." and
status=".$id_san_pham;
$command = Yii::app()->db->createCommand($select)->queryRow();
$Maxid=$command['id'];
$so_luong_ton=$command['so_luong_ton'];
$khoi_luong_ton=$command['khoi_luong_ton'];
$kho_du_tru=$command['kho_du_tru'];
I think, the problem is conflict. It mean that when I get record have max_id, and then before i insert new record, having another process insert new record was inserted.
if such cases happen, so how to handle to fix above problem?
My solution:
$lock = $connection->createCommand('LOCK TABLES `the_kho_chi_tiet_with_id` READ');
$lock->execute();
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
//Insert new record here
TheKhoChiTietWithId::model()->InsertNewRecord(1,300,1,333,1);
$unlock = $connection->createCommand('UNLOCK TABLES');
$unlock->execute();
I lock table to keep no other session work to this table.

Foreign Key not linking correctly

When registering my first user in table 'users' the id is the same value as user_id in the linking table,1, (language). However, when I register another user (id2 in users) the user_id in language is still 1. See SQL:
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`full_name` tinytext CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`user_name` varchar(10) NOT NULL,
`user_email` varchar(30) NOT NULL,
`user_level` tinyint(4) NOT NULL DEFAULT '1',
`pwd` varchar(220) NOT NULL,
`nationality` varchar(30) NOT NULL,
`department` varchar(20) NOT NULL,
`birthday` date NOT NULL,
`date` date NOT NULL DEFAULT '0000-00-00',
`users_ip` varchar(200) NOT NULL,
`activation_code` int(10) NOT NULL DEFAULT '0',
`banned` int(1) NOT NULL,
`ckey` varchar(200) NOT NULL,
`ctime` varchar(220) NOT NULL,
`approved` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
This is my PHP code:
if(empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit')
{
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0'") or
die (mysql_error());
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id']= $id;
sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
Would appreciate any help!
I think this is because your initial select query is selecting all users that are not banned
So need to change the query to filter by the new user:
"SELECT `id` FROM users WHERE `banned` = '0' and id=" . $_SESSION['$user_id'];
The reason why the user_id field kept getting populated as 1 was because mysql_fetch_row was getting the first record which was user id 1.
So if you filter it by the new user, mysql_fetch_row should get the id of the new user.
EDIT
I'm just looking at the code again, and it looks like you do not store the user id in php after you insert it, so your user_id for $_SESSION is null.
So my above example will not work. Instead of the above query, use the following function to get the id of your newly created user. You call this function after you run your insert query. That function will get the new of your newly created user.
mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
EDIT 2
Ok, since mysql_insert_id() didn't work for you, maybe you can try the following. I just changed your select query to order by id desc.
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc")
Just a note, this is probably not the best solution. But on a low traffic website it should be fine. To make the query a bit more accurate, you'd want to search for the user id based on a unique field like a username or email. This would make sure you get the correct id back.
EDIT 3
Here is an example of checking for the user's email. This is just the mysql query, you'll have to adjust this for php. Sorry I'm in class right now.
"SELECT `id` FROM users WHERE `banned` = '0' and email='user#email.com' limit 1

id not changing correctly

If I register a user using this table:
CREATE TABLE IF NOT EXISTS `users`
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`md5_id` VARCHAR(200) NOT NULL,
`full_name` TINYTEXT CHARACTER SET latin1 COLLATE latin1_general_ci
NOT NULL,
`user_name` VARCHAR(10) NOT NULL,
`user_email` VARCHAR(30) NOT NULL,
`user_level` TINYINT(4) NOT NULL DEFAULT '1',
`pwd` VARCHAR(220) NOT NULL,
`nationality` VARCHAR(30) NOT NULL,
`department` VARCHAR(20) NOT NULL,
`birthday` DATE NOT NULL,
`date` DATE NOT NULL DEFAULT '0000-00-00',
`users_ip` VARCHAR(200) NOT NULL,
`activation_code` INT(10) NOT NULL DEFAULT '0',
`banned` INT(1) NOT NULL,
`ckey` VARCHAR(200) NOT NULL,
`ctime` VARCHAR(220) NOT NULL,
`approved` INT(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
)
ENGINE=INNODB
DEFAULT CHARSET=latin1
AUTO_INCREMENT=3;
and then once logged in to 'myaccount.php' use this code to enter values into another table, the language table:
if (empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit') {
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc");
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id'] = $id;
foreach ($_POST as $key => $value) if (empty($err)) {
for ($i = 0;$i < count($_POST["other"]);$i++) {
$native = mysql_real_escape_string($_POST['native'][$i]);
$other = mysql_real_escape_string($_POST['other'][$i]);
$other_list = mysql_real_escape_string($_POST['other_list'][$i]);
$other_read = mysql_real_escape_string($_POST['other_read'][$i]);
$other_spokint = mysql_real_escape_string($_POST['other_spokint'][$i]);
$other_spokprod = mysql_real_escape_string($_POST['other_spokprod'][$i]);
$other_writ = mysql_real_escape_string($_POST['other_writ'][$i]);
$sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert, $link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
}
}
}
All is fine until , for example I register id=3 (in users table) and then log back into id=1 and change their details in the language table, then their user_id in the language table (which is foreign key to id in users table) is 3 when it should be 1. To make things simple, the id in users table should be same as the user_id in the language table. But when going back and changing data in the languages table the user_id stays the same as the last id that registered!
Please help!
This query you have:
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc");
What is the purpose of it? You are assigning to $id the first value it finds, yet the query doesn't look for user name or anything else. You probably want to user $_SESSION['$user_id'] instead of $id as your user's ID.

Categories