if statement to check if mysql row exists, then selecting next query - php

I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?

You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";

You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO

Related

php count 2 parameters error

I'm making a function that brings me the sum of the records in my database that meet 2 conditions.
i start like this
function cuentaticketspendienteempleado($conexion){
$pendientes = (mysqli_query($conexion, "SELECT COUNT(*) AS conteo FROM ticket ")) or die("Error mostrando tickets pendientes: ".mysqli_error($conexion));
$resultados = mysqli_fetch_row($pendientes);
return $resultados[0];
}
I need to add one more field to the account.
the ID department parameter which I want to assign to only tell me the tickets or reports of that department
using the previous function
When I'm trying to account for that user's tickets in that department using this function
function listTicketUnrevisedSupervisor($conexion, $id){
$consulta = mysqli_query($conexion, "SELECT *, COUNT(t.id) as contador_tickets, t.id as id_ticket, u.id as user_id, t.fecha_creacion as t_fcreacion, t.hora_creacion as t_hcreacion
FROM ticket as t
JOIN usuario AS u
ON t.id_usuario = u.id
WHERE t.status <> '3' AND u.id_departamento = ".$id."")
or die("Error listando Ticket: ".mysqli_error($conexion));
return $consulta;
}
i get this
error
Maybe is just the formatting of your post, but the * can't be used on a query when you are selecting other specific fields, you can use the function like this
function listTicketUnrevisedSupervisor($conexion, $id) {
$query = "SELECT t.field1, u.field_2, t.id as id_ticket, u.id as user_id, "
. "t.fecha_creacion as t_fcreacion, "
. "t.hora_creacion as t_hcreacion "
. "FROM ticket as t "
. "JOIN usuario AS u ON t.id_usuario = u.id "
. "WHERE t.status <> '3' "
. "AND u.id_departamento = " . $id . " "
. "ORDER BY t.id DESC ";
if($consulta = mysqli_query($conexion, $query)){
return $consulta;
} else {
die("Error listando Ticket: ".mysqli_error($conexion));
}
}
Or just select everything
function listTicketUnrevisedSupervisor($conexion, $id) {
$query = "SELECT * "
. "FROM ticket as t "
. "JOIN usuario AS u ON t.id_usuario = u.id "
. "WHERE t.status <> '3' "
. "AND u.id_departamento = " . $id . " "
. "ORDER BY t.id DESC ";
if($consulta = mysqli_query($conexion, $query)){
return $consulta;
} else {
die("Error listando Ticket: ".mysqli_error($conexion));
}
}
Counting the rows
$num_rows = mysqli_num_rows($consulta);
mysqli_query documentation (en)
Here you can check the documentation about mysqli_query (En EspaƱol Juan)
Hope my answer helps you.
Edit, fetch all the results
You can do it with a procedure like this one
function getTheAssocArrayOfMyQuery($consulta){
$return= array();
while ($row= mysqli_fetch_assoc($consulta)) {
array_push($return, $consulta);
}
return $return;
}
Or, using mysqli_fetch_all()
$this_is_the_array_i_will_use = mysqli_fetch_all($consulta,MYSQLI_ASSOC);
mysqli_fetch_all() manual

PHP Run query on SHOW TABLES results

How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.

PHP MySQL statement with multiple variable components

I am producing an API that takes in certain parameters, carries out an algorithm and returns the results. As part of this process I have several different clauses that can go into the SQL statement based on what is sent to the API. This has produced many sections of this format:
if(isset($_GET['val'])) {
$sqljoin = " INNER JOIN b ON b.1=a.1 "
$sqlwhere = " WHERE b.2 = " . $_GET['val'];
}
$sql = "SELECT * FROM a " . $sqljoin . $sqlwhere;
Which was fine initially, but now I have approximately 6 different clauses going into it, both with a JOIN and a WHERE clause. Is there a better way of structuring this?
this may help you .
$sql = "SELECT * FROM a ";
$where = " WHERE 1=1 ";
if(isset($_GET['val'])) {
$sqljoin = " INNER JOIN b ON b.1=a.1 "
$sqlwhere = " AND b.2 = " . $_GET['val'];
}
if(isset($_GET['val2'])) {
$sqljoin2 = " INNER JOIN b2 ON b2.1=a.1 "
$sqlwhere2 = " AND b2.2 = " . $_GET['val2'];
}
$fullquery = $sql . $sqljoin . $sqljoin2 . $where . $sqlwhere . $sqlwhere2 ;
Some notes:
Your code is under sql injection vulnerability. you should escape your variables by
$_GET['val'] = mysql_real_escape_string($_GET['val']);
you should switch to PDO or MYSQLI.

PHP MySQL - Inner Join only if not null

I have a mysqli SELECT query that is using an Inner Join and I noticed a big problem: it doesn't select rows where the column value for the condition is null (because NULL doesn't exist in the second table). Here's my code:
<?php
$sql = mysqli_connect(/* CONNECTION */);
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"INNER JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
$results = mysqli_query($sql, $query);
if(!isset($data)) $data = array(); $cc = 0;
while($info = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(!isset($data[$cc])) $data[$cc] = array();
///// FROM TABLE equipments /////
$data[$cc]['EQUIPMENT_ID'] = $info['EQUIPMENT_ID'];
$data[$cc]['DESCRIPTION'] = $info['DESCRIPTION'];
$data[$cc]['LOCATION'] = $info['LOCATION'];
$data[$cc]['PROJECT_NAME'] = $info['PROJECT_NAME'];
$data[$cc]['JOB_SITE_ID'] = $info['JOB_SITE'];
///// FROM TABLE jobsites /////
$data[$cc]['JOB_SITE'] = $info['JOB_SITE_NAME'];
$cc++;
}
print_r($data);
?>
So, as I said, the code returns values but only if the column "JOB_SITE" inside "equipments" has a jobsite id (not null). The ugly solution is to create a row inside the table "jobsites" with a jobsite_id named "empty", but if I can skip this, I will.
Is there a way to join only if e.JOB_SITE is not null ?
You can use LEFT JOIN in SQL query.
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"LEFT JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
This query will return NULL VALUE for column JOB_SITE_NAME if there is no row matching jb.JOBSITE_ID in equipments table

Optimizing PHP script

I have a working script that selects image fields in all tables and empty their values if the physical file doesnt exist.
$query1 = "SELECT table_name,column_name
FROM information_schema.columns
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_row($result1)){
if (!strpos($row1[0],'backup') > 0){
$sql = "Select COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '".$row1[0]."' AND EXTRA = 'auto_increment'";
$resultcol = mysql_query($sql);
$rowcol = mysql_fetch_row($resultcol);
$query2 = "SELECT " . $row1[1] . ", " .$rowcol[0] . "
FROM " . $row1[0] . "
WHERE " . $row1[1] . " != '' AND " . $row1[1] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2)){
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0])){
$sql = "UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE " . $rowcol[0]. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
The script is working fine, but it takes time though, I was wondering if there is a smarter way (more optimized) to get the same function ? Thanks
You have several options.
The first, and IMHO the best option - is to use an ORM -
I recommend Idiorm, Doctrine, or Propel.
Then, you would use something like (in idiorm) fetch_all and loop through that, instead of through the mysql_fetch_row()
Second, you should switch to mysqli -- the functions you are using are deprecated in PHP5.5
Third -- you could just use either mysql_fetch_array or mysql_fetch_all (I'm not sure, but I would be on the latter)
The key thing here is:
Do not loop mysql functions.
Performance wise the problem is that you are looping through a result set, and performing queries for each row.
However with your output it is difficult to eliminate this. Otherwise you might be able to do the whole script in a single SQL statement.
Minimal clean up to just remove one of the selects:-
<?php
$query1 = "SELECT a.table_name, a.column_name, b.COLUMN_NAME AS auto_inc_col
FROM information_schema.columns a
INNER JOIN information_schema.columns b
ON a.table_name = b.table_name AND b.EXTRA = 'auto_increment'
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_assoc($result1))
{
if (!strpos($row1['table_name'],'backup') > 0)
{
$query2 = "SELECT " . $row1['column_name'] . ", " .$row1['auto_inc_col'] . "
FROM " . $row1['table_name'] . "
WHERE " . $row1['column_name'] . " != '' AND " . $row1['column_name'] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2))
{
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0]))
{
$sql = "UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE " . $row1['auto_inc_col']. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
?>

Categories